I am attempting to solve, using C, question 3 on Project Euler. I am having trouble with the large integer that is in the question - int and long got me an "overflow" warning, and my program didn't print the result to the console. So I switched to a 'long long' type, the warning is gone but the console still isn't printing the answer, which makes me think I have a mistake in my code.
#include <stdio.h>
int main()
{
long long largest=0;
long long div=2;
long long i = 600851475143;
while(div<i)
{
if(i%div == 0)
{
largest=div;
}
div++;
}
printf("%I64d\n", largest);
return 0;
}
I am using Mingw as a compiler for this, on Windows 7.
Use %lld
to print long long int
type data.
printf("%lld\n", largest)
or change I
in your format specifier to l
.
The code is OK..Its just that it is taking too long to run.The following code prints out the steps.
while(div<i)
{
printf("%lld\n",div);
if(i%div == 0)
{
largest=div;
}
div+=1;
}
As per algorithm point i would recommend you to initialize div = 600851475143/2
and count backwards
尝试%ll
,它会正常工作
printf("%ll\n", largest);
please use %lld
as format specifier. for more information refer link
#include <stdio.h>
int main()
{
long long largest=0;
long long div=2;
long long i = 600851475143;
while(div<i)
{
if(i%div == 0)
{
largest=div;
break;//out of loop
printf("%lld\n", largest);//or add this ,I don't think so
}
div++;
}
printf("%lld\n", largest);
return 0;
}
maybe that's what you want,maybe not...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.