简体   繁体   中英

Why my printf does not work?

The question is to find the largest prime factor of the number 600851475143, and my code is:

#include <stdio.h>
#include <math.h>
int main()
{
    float i,x;
    float a,y;
    for(a=2;a<=600851475143;a++)
    {
        y=fmod(600851475143,a);
        if(y==0)
        {
            int sum=0;
            for(i=2;i<=a/2;i++)
            {
                if(fmod(a,i)==0)
                {
                    sum=1;
                    break;
                }
            }
            if(sum==0&&a>x)
            x=a;
            // printf("%f\n",x );
        }

    }
    printf("%f\n",x );
    return 0;
}

Why is my printf function not working? When I put printf above (shown in comments), it works, but the last printf does not work. Why?

I don't think the printf function have problem, when you run the program, it needs too much time, so the last printf didn't run, you should choose another faster algorithm for optimization.

#include <stdio.h>
#include <math.h>
int main()
{
    float i,x;
    float a,y;
    for(a=2;a<=600851475143;a++) // it needs too much time!
    {
        y=fmod(600851475143,a);
        if(y==0)
        {
            int sum=0;
            for(i=2;i<=a/2;i++)  // this algorithm is O(N^2)
            {
                if(fmod(a,i)==0)
                    {
                        sum=1;
                        break;
                    }
            }
            if(sum==0&&a>x)
            x=a;
            printf("%f\n",x );
        }
    }
    printf("%f\n",x ); // needs too much time to go here
    return 0;
}
#include <stdio.h>
#include <math.h>
int main()
{
long double i,x, a, y;
    for(a=2;a<=600851475143;a++)
    {
        y=fmod(600851475143,a);
        if(y==0)
        {
            int sum=0;
            for(i=2;i<=a/2;i++)
            {
                if(fmod(a,i)==0)
                    {
                        sum=1;
                        break;
                    }
            }
            if(sum==0&&a>x)
            x=a;
            printf("%Lf\n",x );
            //break;
            }

  }
printf("%Lf\n",x );
return 0;
}

if there is no break it will find a number at a condition but will return to the for and keep looking for another. That is why you use a break to find the first one. To find more I recommend using "long double" data type.

which is a Real floating-point type, usually mapped to an extended precision floating-point number format. Actual properties unspecified. Unlike types float and double, it can be either 80-bit floating point format, the non-IEEE "double-double" or IEEE 754 quadruple-precision floating-point format if a higher precision format is provided, otherwise it is the same as double.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM