Could you please help me?
I'm a beginner at C and my code doesn't work.
I'm trying to determine largest prime factor of 600851475143 and when I run the code, it just does nothing. Trying with smaller number however works.
long i;
for (i = 600851475143; i > 1; i--)
{
if (600851475143 % i == 0)
{
printf("%d\n", i);
}
};
First of all, the correct way to print a
longis not%dbut%ld(d = decimal, ld = long decimal). Iflongandinthave different sizes on your system (which is not unusual), the results would not print correctly to begin with.Next possible problem is that
600851475143is more than fits into a32 bitvariable, yetlongis only guaranteed to be at least32 bit. It may be bigger than that, but only32 bitsare guaranteed. So are you sure thatlongis big enough on your system?Try
if it says
8, everything is fine, if it says only4,longis not sufficient and you need to uselong longinstead (and%lldforprintf, lld = long long decimal).Last but not least, you are aware that your loop needs to do 600 billion iterations, aren't you? Even if you have a very fast system with a very fast CPU this will take quite some time to complete. So you will see
600851475143printed to the screen immediately, but it will take quite some time before your code terminates (or finds another divisor, in case this is not a prime number).Optionally: Instead of writing
600851475143, you may write600851475143LLto let the compiler know you want this number to be of typelong long. It seems like the C 2011 standard doesn't require this any longer (numbers are automatically treated aslongorlong longif required), yet I know that pior to C 2011 some compilers least issued a warning for numbers being bigger thanint(or bigger thanlong).