Start New Discussion within our Software Development Community

when i try to do the following,

double root_value, c;
int d;
d=0;

printf("%.0f", root_value);
for(c=2; c<root_value;c++)	
			{
			if(c !=root_value)
				{	
				if(fmod(root_value,c)==0)
                                       {
					d = 1;
                                        }
				}
			}
				
		if(d == 1)
			{
			printf("not prime\n");
                        }
                 else
                          printf("is prime\n");

now its part of a program to determine if a number prime

using my data set of
11
24
2134213412

the program prints the origianl value then can process and correctly determine that 11 is prime and 24 is not prime by printing the corresponding message. however when it encounters the 10 digit number, it prints the number itself but never goes through the loop and prints the corresponding message.

any idea why it wont work?
it works with 6 digit numbers... double should hold more that that though

It works but too slowly (over two billions unnecessary loops) ;)
Break the loop when you know that it's not a prime (and try to optimize code because it's a brutal force slow algorithm):

... // positive root_value only...
    double c = 2.0;
    bool prime = true;

    root_value = floor(root_value); // clear fractional
    if (root_value > 2.0 && fmod(root_value,2.0) == 0.0)
        prime = false;
    else if (root_value > 3.0) {
        double third = floor(root_value/3.0+0.5);
        printf("%.0f ...wait a bit...\n",root_value);
        for (c = 3.0; c <= third; c += 2.0) { // think why 2...
            if (fmod(root_value,c) == 0.0) {
                prime = false;
                break;
            }
        }
    }
    printf("%.0f is %sprime\n",root_value,prime?"":"not ");
    if (!prime) {
        double x = root_value / c;
        printf("%.0f == %.0f*%.0f\n",root_value,c,x);
    }
This article has been dead for over six months. Start a new discussion instead.