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.
}
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.
}
You have two options:
Stick with the %
operator, then you're required to cast the inputs to int
s
if(((int)x % (int)j) == 0)
Include math.h
and then use fmod
:
if(fmod(x, j) == 0)
您的直接问题可以通过fmod
解决,但是出于高价素数的目的,您最好还是查看一个大整数类,比如http://sourceforge.net/projects/cpp-bigint/因为你真正想要的是整数数学,并且随着事情的发展,使用浮点数可能会导致问题。
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.