I was on hackerrank, and I ran into a very weird problem. The problem is "You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our answer is 2.". Here is my solution:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t, count;
cin >> t;
for (int i = 0; i < t; i++) {
int n, copy;
cout << "i: " << i << " ";
cin >> n;
cout << "n: " << n << " ";
copy = n;
count = 0;
while (copy > 0) {
if (n % (copy % 10) == 0)
count++;
copy = copy/10;
}
cout << "\n" << count << "\n";
}
return 0;
}
t is the number of test cases, and n is the number to be tested. I can input any number I want into t without problems. However, if I input a number with a zero into n, I get a floating point exception error. The error occurs before the second cout statement. Other numbers work fine (so, for instance, 1024 gives an error, but 1124 is fine). I ran this code on the hackerrank website. Can someone please explain what is going on?
You can't mod divide by 0. Try to redesign your algorithm so that you avoid trying to perform that operation. Perhaps check
copy % 10 == 0
then just skip that case. The reason that it is afloating point exception
and not adivide by zero exception
is described in this stack exchange post