Project Euler 3 in c,code processing for too long for large numbers? -


it taking forever give answer,it seems processing answer? have seen similar questions please tell me wrong 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 problem:

the prime factors of 13195 5, 7, 13 , 29. largest prime factor of number 600851475143 ?

it's not code wrong in incorrect, it's wrong in inefficient.

let's @ code tests if number prime:

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

if testing of number 7919 (which prime), loop run 4,000 times.

but condition much stronger. if wrote:

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

then prime number testing still correct - has run 88 times, vast improvement. asymptotically you've changed linear (in n) algorithm testing primality 1 runs in root n time - can test primality faster, won't have @ least first 50 problems in project euler.

my version of code project euler problem isn't far yours except prime number checking (and it's in java) , runs in 0.023631seconds.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -