Search code examples
c++divide

Why is a divide by error coming?


A divide by zero error is being shown in the following code.. I am using dosbox 0.74 compiler

int chkpm(int,int);
void main()
{
    int num,i,count=-1;

    cout<<"Enter a number\n";
    cin>>num;
    for(i=0;i<=num/2;i++)
    {
        if(num%i==0)
        {       //test
            `enter code here`cout<<"num%i=0";

     count=chkpm(num,i);
        }
        if(count>0)
        {
            cout<<i<<" ^ "<<count;
        }
    }
    cout<<"bye test \n";
    getch();
}
int chkpm(int num,int i)
{
    int j,flag=0; //flag will be true if i is not prime factor
    int count=0;        //to calculate power of prime factor
    for(j=0;j<=i/2;j++)  //to check for prime
    {
        if(i%j==0)  //check for divisibility
        {
            flag=1; //that means i is not prime
            break;
        }
    }
    if(flag==0)   //if factor i is prime,flag is 0
    {
        while(num%i==0) //keep dividing prime factor by num
        {       count++;  //to count power
            num=num/i;
        }
        return count;
    }
    else return -1;        //when flag=1, i.e. factor not prime
}

Error is showing when I re-execute the code, not at compile time I've tried all kinds of inputs ranging from zero to positive numbers.........

Any help would be appreciated


Solution

  • for(i=0;i<=num/2;i++)
    {
        if(num%i==0)
        ...
    }
    

    Here i will start from value 0. % means modulo, which actually implies that a division will take place, thus you divide by zero in the if condition.

    Inside your function you have a similar logical error:

    for(j=0;j<=i/2;j++)  //to check for prime
    {
        if(i%j==0)
        ...
    }
    

    If you don't fix main(), then the function will have i equal to zero which will cause more damage.


    You use void main(), instead of the typical int main(). You might want to take a look at this relevant question. Then a return 0 before you exit main() should be added.