What is causing SIGFPE error in this code?

i am trying to count total number of subarrays which are divisibleby a given number .

#include <iostream> 
using namespace std; 
int countsubarray(int array[], int n, int k) 
    int count = 0;  
    int i, j, mul;  
    for (i = 0; i < n; i++) 
        if (array[i]%k==0) 
        mul = array[i]; 
        for (j = i + 1; j < n; j++)  
            mul = mul * array[j];  
            if (mul%k==0)  
    return count; 

int main() 
    int n,k;
    int array[n],i;
    int count = countsubarray(array, n, k); 
    cout << count << "\n"; 

What test input is causing it to SIGFPE?

run time error is poping up .
and showing SIGFPE

On Codechef, when you submit? If so, what Problem?

Or on your local machine, using an IDE/ command-line? If so, what test input are you providing?

on local ide . i am providing input
6 2
1 2 3 4 5 6

Hmmm … odd. I can’t immediately see anything that could cause a crash, and for me (after adding the missing #includes) it prints out the number 18:

>echo "6 2
1 2 3 4 5 6" | ./a.out

which header file is missing?

#include <iostream>

in my program#include<iostream> is present but still showing error.

Dunno then - the only thing I can think of is that the input is not being provided correctly, and n and k are keeping their undefined values (though I thought C++11 was supposed to set them to 0 in the case of an unsuccessful formatted extraction?).

Can you add:

cout << "n: " << n << " k: " << k << endl;

under the line:


and re-run as you have been doing with the same test input and post the output?

ok let me change and check that also.

1 Like

got the error but now this program is taking long time . is there any efficient way to find subarray having product equal to a given number ?

Are u checking for overflow?

SIGFPE is a floating point error

It can occur for mainly 3 reason

  1. division by zero

  2. modulo operation by zero

  3. integer overflow (when the value you are trying to store exceeds the range) - trying using a bigger data type like long.

now i am checking for overflow(time limit exceeded) ,SIGFPE error was fixed .

What was the error? :slight_smile:

Also, what precisely are you trying to do? Are you trying to find the “subarray having product equal to a given number”, as you state here, or “count total number of subarrays which are divisible by a given number” as you state in the original post? The two are not equivalent.

1 Like

i want number of subarrays having product equal to a given number.

1 Like

You mean number of subarray?

yep total number of such type of arrays

Assuming no overflow is there, you can use prefixing/precomputation. And use two nested loop to count the subarray.

This has time complexity as O(n²)

However you can optimize it to O(n) using two pointers, you can read about it online

oh i will check .