-3

Hey what wrong with this code. when run this code its showing some error floating point exception(core dumbed).I used g++ to compile this program.

#include <iostream>
using namespace std;

int checkprime(int num){
int ch=0;
for (int n=2;n<num;n++){ 
    if (num%n==0){ ch=ch+1 ;}}
if (ch==0){return num;}
else{return -1; }
}


int main(){
int prt=0;int a=2;long long int pri=600851475143;int arr_pr_fac[100];
int re;
while(a<pri){
    a++;
    if (pri%a==0){ re=checkprime(a) ;
        if (re>0){arr_pr_fac[prt]=re;prt++;cout<<re<<endl;}

    }
}
for(int th=0;th<4;th++){cout<<arr_pr_fac[th]<<endl;};
}
  • You forgot to post some little details: Decription of what the code is supposed to do. Required outputs for inputs used. The exact error message, (NOT 'some error'). Details of what debugging you have done ,eg. which line generates the error and the values of all relevant vars at that point. Things like that.. – Martin James Feb 14 '16 at 16:19

3 Answers3

1

Here is one problem:

    int a = 2; long long int pri = 600851475143;
    // ...
    while (a < pri) {
    a++;
    if (pri%a == 0) {  // <-- a will be 0 at some point

Since you're incrementing a, it will eventually wrap around to 0 due to a only being a signed int, and pri being a larger integer type (long long). Once that happens, taking the modulus of 0 will yield a divide by zero error (which is undefined behavior).

In addition, your while loop will never terminate, since a < pri will always be true. (Admittedly, with such a large value for pri the loop will run a long time, almost as if it won't terminate).

The correction is that you should make a and possibly all your int types (variables, return types from functions, array types, etc.) long long to avoid this and possible other overflow errors.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
0

As you declare long long int pri=600851475143. We are assigning values to a upto pri. Upto a=32767 everything works fine. but after it turns to zero rather a=32768. therefore in statement if (pri%a==0) when a =0 gives floating point exception. sol: Declare a as long long int.

-1

It is probably overflowing the array. Maybe use std::vector.

There are other major problems with the algorithm, assuming it is supposed to get prime factors.

Rob L
  • 2,351
  • 13
  • 23