Question

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.

Was it helpful?

Solution

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

OTHER TIPS

Use %lld to print long long int type data.

printf("%lld\n", largest)  

or change I in your format specifier to l.

Try %ll and it will work fine

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...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top