-1

It is taking forever to give the answer,it seems like it is just processing the answer? I have seen similar questions but please tell me what is wrong with this code?

#include<stdio.h>
main()
{
    int flag=0;
    unsigned long long int j,z,ino,i;
    scanf("%llu",&ino);
    for(i=2;i<=ino/2;i++)
    {
        flag=0; 
        if(ino%i==0)
        {
            for(j=2;j<=i/2;j++)
            {
                if(i%j==0)
                {
                    flag=1;
                }
            }

            if(flag==0)
            {
                z=i;
            }
        }
    }

printf("%llu",z);
}

Here's the problem:

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
  • 1
    Please format your code properly. – Paul R Apr 07 '14 at 07:22
  • 1
    Please format your code correctly. – Jabberwocky Apr 07 '14 at 07:22
  • 1
    That's a tremendously inefficient code for finding out all the prime divisors of a given number `ino`, ok. But what's the question? – raina77ow Apr 07 '14 at 07:26
  • 3
    pick a number. Let's say 1000000. Your outer loop will loop 500000 times. Your inner loop will loop 125000 times on average. So just for a number like a million you'll loop 32 billion times. How many times will you loop for a number like 600 billion? – Art Apr 07 '14 at 07:27
  • The problem is in scanf. Refer this post http://stackoverflow.com/questions/5997258/strange-unsigned-long-long-int-behaviour – abhilb Apr 07 '14 at 07:31
  • 1
    Can you copy the problem statement into the question? – Joni Apr 07 '14 at 07:32
  • loop does not end ino is too large. Can be reduced during processing by dividing by a factor. – BLUEPIXY Apr 07 '14 at 08:38

1 Answers1

0

It's not that the code is wrong as in incorrect, it's wrong as in inefficient.

let's just look at your code that tests for if a number is prime:

            for(j=2;j<=i/2;j++)
            {
                if(i%j==0)
                {
                    flag=1;
                }
            }

If you are testing the primarily of the number 7919 (which is prime), your loop will run almost 4,000 times.

But your condition could be much much stronger. If you wrote:

        for(j=2;j<=sqrt(i);j++)
        {
            if(i%j==0)
            {
                flag=1;
            }
        }

Then your prime number testing is still correct - but it only has to run 88 times, a vast improvement. Asymptotically you've changed from a linear (in n) algorithm for testing primality to a one that runs in root n time - you can test for primality faster, but you won't have to for at least the first 50 problems in Project Euler.

My version of the code for this project Euler problem isn't far from yours except from the prime number checking (and it's in Java) and it runs in 0.023631seconds.

Joe
  • 4,000
  • 7
  • 29
  • 49