Question

This code is working perfectly until 100000 but if you input 1000000 it is starting to give the error C++ 0xC0000094: Integer division by zero. I am sure it is something about floating points. I tried all the combinations of (/fp:precise), (/fp:strict), (/fp:except) and (/fp:except-) but had no positive result.

#include "stdafx.h"
#include "time.h"
#include "math.h"
#include "iostream"
#define unlikely(x)(x)

int main()
{
    using namespace std;
    begin:
    int k;
    cout<<"Please enter the nth prime you want: ";
    cin>>k;
    int cloc=clock();
    int*p;p=new int [k];
    int i,j,v,n=0;
    for(p[0]=2,i=3;n<k-1;i+=2)
    for(j=1;unlikely((v=p[j],pow(v,2)>i))?!(p[++n]=i):(i%v);++j);
    cout <<"The "<<k<<"th prime is "<<p[n]<<"\nIt took me "<<clock()-cloc<<" milliseconds to find your prime.\n";
    goto begin;
}
Was it helpful?

Solution

The code displayed in the question does not initialize p[1] or assign a value to it. In the for loop that sets j=1, p[j] is used in an assignment to v. The results in an unknown value for v. Apparently, it happens to be zero, which causes a division by zero in the expression i%v.

As this code is undocumented, poorly structured, and unreadable, the proper solution is to discard it and start from scratch.

Floating point has no bearing on the problem, although the use of pow(v, 2) to calculate v2 is a poor choice; v*v would serve better. However, some systems print the misleading message “Floating exception” when an integer division by zero occurs. In spite of the message, this is an error in an integer operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top