Integer division by zero c++

3

I have to write a program that inputs a number and outputs the highest divisor of it and then the highest divisor of the divisor and so on, until it reaches a prime. But I keep geting : "Unhandled exception at 0x00eb1504 in primefinder.exe: 0xC0000094: Integer division by zero."

I guess its the "num%i" that causes it but "i" can't be zero since its "num/2".

#include <iostream>

using namespace std;

int main(){
    unsigned int i=666, num;
    cout << "Enter number";
    cin >> num;
    while(i>1){
        i = num/2;
        while(num % i == 0){
            i--;
        }
        cout << i << endl;
        num=i;
    }
    cin.get();
    return 0;
}
c++
asked on Stack Overflow Feb 15, 2014 by Zeor137 • edited Feb 16, 2014 by Zeor137

3 Answers

1

As ooga mentions in his comment, 1/2 (and 0/2) will equal zero due to integer math.

To avoid division by 0 here, change cin >> num; to:

do
{
    cin >> num;
} while (num <= 1);

This will continue prompting until a valid number is input.

EDIT: Cornstalk's Answer properly points out that you must guard the inner-most while loop with i > 0 && num % i == 0.

answered on Stack Overflow Feb 15, 2014 by schumacher574 • edited May 23, 2017 by Community
1

If i is zero, then num % i can result in this error. When can this happen? Let's say you put the number 2 as input. Then it executes as:

    i = num/2; // i is now (2 / 2) = 1
    while(num % i == 0){ // 2 % 1 = 0, so the loop continues
        i--; // i is now zero, so the next loop iteration will cause a division by zero!
    }

So you need to do:

while(i > 0 && num % i == 0)

to make sure that i is never zero.

answered on Stack Overflow Feb 15, 2014 by Cornstalks
0
int main(){
    unsigned int i=666, num;
    cout << "Enter number";
    cin >> num;
    while(i>1){
        i = num/2;

Why do you initiliaze i with 666 and then immediately assign i=num/2

By the way, "that inputs a number and outputs the highest divisor of it and then the highest divisor of the divisor and so on" seems like a good candidate for a recursive algorithm.

answered on Stack Overflow Feb 16, 2014 by macroland

User contributions licensed under CC BY-SA 3.0