Error "Floating point exception" Prime listing program

I am working on a way to efficiently check to see if an integer is prime, mainly by checking to see if it is divisible by all the primes that preceede the inter-to-be-checked's square root. I do this by initializing an array of SIZE, and setting its first value to the first prime number, 2. The program then stores any prime number that it comes across sequentially into the array.

the array and the number being checked are passed to a function that takes the root of the inter-to-be-checked's, mod = num % prmStor[index], and then it checks to see if mod = 0, if so, the loop stops, and the function tells the program that the checked number is composite. If the mod != 0, the loop iterates and checks to see if the next value stored in the array mod = num % prmStor[index] = 0.



I am working with Ubuntu's Jaunty Jack and am using CodeBlocks 8.02.

The program compiles without error but when I run it, it gives me an error after I enter in the first value. The error is "floating point exception." In researching floating point exceptions I found that it arises when your code is trying to something it is not allowed to do (like sqrt of a negative number). I cannot find where that error is in my code, however.

I think I may need to do a type conversion or use a roof function to make the square root of the number being checked an integer. if so, what's a simple syntax to do so?

I would appreciate any help in finding the error in my code. Thanks.

Here is my code:




#include <iostream>
#include <cmath>

using namespace std;


int main()
{
bool check;
int primes = 1;
int index = 0;

const int SIZE = 100;
int prmStor[(SIZE-1)];

prmStor[0] = 2;

cout << "This program will display the first " << SIZE <<" primes.";
cout << endl << endl << endl;



for ( int count = 1 ; primes <= SIZE ; count++ )
{


check = primeCheck ( count, prmStor );

if (check == true)
{
cout << count << ". " ;
prmStor[(index)] = count;
primes++;

if ( primes%10 == 0 )
{
cout << " ((row " << primes/10 << endl;
}
}
index ++;
}

return 0;
}



bool primeCheck ( int num, int prmStor[] )
{
bool check = true;
int mod;

num = sqrt(num);

{
for ( int index = 0 ; prmStor[index] <= num || check == true ; index++ )
{
mod = num % prmStor[index];

if ( mod == 0 )
{
check = false;
}
}
}

return check;
}
Topic archived. No new replies allowed.