Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

c++ - Getting the error floating point exception: 8

I have no idea why g++ doesn't like my code. It ran fine in java. Any insights would be greatly appreciated.

#include<iostream>

using namespace std;

bool isPrime(long number);

int main(){
const long number = 600851475143;
long max = 0;
for(long i= 0; i*i <= number; i++)
    if(number % i == 0 && isPrime(i))
        max = i;
cout<< max << endl;

return 0;
}

bool isPrime(long number){
if(number <= 1) return false;
if(number == 2) return true;
if(number % 2 == 0) return false;

for(long     i= 3; i*i <= number; i+=2)
    if(number % i == 0)
        return false;
return true;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const long number = 600851475143;

There is overflow, long can't hold that big number.

see this link

LONG_MAX is 2147483647

try:

const unsigned long long number = 600851475143;
unsigned long longmax = 0;

Edit:

You can't % against 0, i starts from 0

for(long i= 0; i*i <= number; i++)
           ^^
{
    if(number % i == 0 && isPrime(i))
               ^^^
{
   max = i;
   cout<< max << endl;
}

}

Minor change to a working version:

bool isPrime(unsigned long long  number);

int main(){

    const unsigned long long number = 600851475143;
    unsigned long long max = 0;
    for(long i = 1; i*i <= number; i++)
    {
        if(number % i == 0 && isPrime(i))
        {
            max = i;
            cout<< max << endl;
        }
    }
    return 0;
}

bool isPrime(unsigned long long  number)
{
    if(number <= 1) return false;
    if(number == 2) return true;
    if(number % 2 == 0) return false;

    for(unsigned long long i= 3; i*i <= number; i+=2)
    {
        if(number % i == 0)
        {
            return false;
        }
    }
    return true;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...