Kundan Kumar
Kundan Kumar

Reputation: 21

Unable to find the floating point exception

This code is showing floating point exception. I know why this error occurs, but I am not able to find the error in this code.

#include<bits/stdc++.h>

using namespace std;

typedef long long int ll;
#define MAX 10005

vector<int> build_sieve() {
    bool arr[MAX];
    for(int i=2;i<=MAX-1;i++) {
        arr[i]=true;
    }

    arr[0]=false;
    arr[1]=false;
    for(int i=2;i*i<=MAX-1;i++) {
        if(arr[i]==true){
            for(int j=i*i;j<=MAX-1;j=j+i) {
                arr[j]=false;
            }
        }
    }

    vector<int>  v;
    for(int i=2;i<=MAX-1;i++) {
        if(arr[i]==true){
            v.push_back(i);
        }
    }
    return v;
}

int main() {
    // int t;
    // cin>>t;
    vector<int> v =  build_sieve();
    cout<<"Prime no.s"<<endl;
    for(auto i = v.begin();i!=v.end();i++) {
        cout<<*i<<" ";
    }

    int t;
    cin>>t;
    while(t--) {
        int n,len;
        cin>>n>>len;
        ll arr[len];
        for(int i=0;i<=len-1;i++) {
            cin>>arr[i];
        }
        set<ll> s;
        for(int i=0;v[i]<=n&&i<=100001;i++) {
            for(int j=0;j<=len-1;j++) {
                if((arr[j]%v[i])==0) {
                    s.insert(v[i]);
                    cout<<v[i]<<" "<<arr[j]/v[i]<<endl;
                    s.insert(arr[j]/v[i]);
                }
            }
        }
        cout<<s.size()<<endl;
    }
}

Upvotes: 0

Views: 64

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

Some systems report a floating point exception for an integer divide by zero. So how can your code get one of those? You divide by v[i] (the modulo operator % is a division). How can v[i] be zero? Because you're accessing past the ends of the v vector.

When you construct v, your list of primes, you only add numbers less than MAX, which is 10005. However, in your for loop in main, you limit yourself to much larger indexes (i <= 100001), which is the count of primes, not the number that is prime. Once you get past the end of v, you get into Undefined Behavior, which eventually results in the exception.

Upvotes: 1

Related Questions