0

I get a floating point exception when running this program:

#include <stdio.h>

int check(int n)
{
    int ii=0;
    int jj=0;
    int sum_of_dividors=0;
    int sum_of_dividors2=0;
    for (ii=0;ii<n;ii++){
        for (jj=0;jj<ii;jj++){
            if(ii%jj==0)
            {
              sum_of_dividors=sum_of_dividors+jj;
            }
        }
        if(sum_of_dividors<n || ii<n){
            for (jj=0;jj<sum_of_dividors;jj++){
                if(sum_of_dividors%jj==0)
                {
                sum_of_dividors2=sum_of_dividors2+jj;
                }
            }
        if (sum_of_dividors2==ii){
            printf("%d and %d,",ii,sum_of_dividors);
        }
        }
    sum_of_dividors=0;
    sum_of_dividors2=0;
    }
}


int main()
{
    int n;

    printf("Enter n ");
    scanf("%d",&n);
    printf("%d",check(n));
}

The code's purpose is to check the closest pair of amicable numbers to the number (n) that the user have entered.

underscore_d
  • 6,309
  • 3
  • 38
  • 64

4 Answers4

1

If you check with GDB, the problem is in the line

if(ii%jj==0)

You Can't Mod Zero?

Jesferman
  • 1,049
  • 7
  • 12
1

C 6.5.5 [ISO/IEC 9899:2011] states:

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

So, modulo by zero invoked undefined behaviour in C.

msc
  • 33,420
  • 29
  • 119
  • 214
0

You cannot mod % by 0 ! It will give undefined behavior !

Bharadwaj
  • 135
  • 1
  • 1
  • 7
0

You should apply for %, apart from the result, exactly the same constraints as /. Therefore, in C and C++, you can't mod by 0. If you want to have a behavior where X % 0 equals X, you'll have to check specifically for X to be equal to 0, and return it.

PoutchiPatch
  • 168
  • 1
  • 11