tags:

views:

80

answers:

3

I have a program I am writing that lists 100,000 prime numbers. It works fine for 10 numbers, but after so many numbers they turn into negative values. I changed the ints to long ints and that did not change anything, then I changed them to doubles and I get the error listed in the title. What should my variable be? Keep in mind I am still new to programing. I also looked at some previous posts and did not see the answer.

 int is_prime(double x,char array[]){
 //doesnt use array but I put it in there

     double j=2;//divider
     for(j=2;j<=pow(x,0.5);j++){
         if((x%j==0)){
             return(0);
         }   //isnt prime  
     }
     return(1);// because it is prime.
 }
+2  A: 

You can't use a double with the operator, you must have an int.

You should: #include <math.h> and then use the fmod function.

if(fmod(x,j)==0)

Full code:

 #include <math.h>
 int is_prime(double x,char array[]){
 //doesnt use array but I put it in there

     double j=2;//divider
     for(j=2;j<=pow(x,0.5);j++){
         if(fmod(x,j)==0){
             return(0);
         }   //isnt prime  
     }
     return(1);// because it is prime.
 }
thyrgle
awesome, I never would have figured that out on my own.
pisfire
I'm pretty sure you want `fmod`, not `modf`...
Mark E
@Mark: Oops, thanks for pointing that out.
thyrgle
+2  A: 

You have two options:

  1. Stick with the % operator, then you're required to cast the inputs to ints

    if(((int)x % (int)j) == 0)
    
  2. Include math.h and then use fmod:

    if(fmod(x, j) == 0)
    
Mark E
A: 

Your immediate question can be solved with fmod, but for your purpose of high-value prime numbers, you may be better off looking at a big-integer class, like that at http://sourceforge.net/projects/cpp-bigint/ since what you really want is integer mathematics, and using floats might cause problems as things progress.

Jon Hanna