Search code examples
cmathcounterdivisiondivider

Getting one too few divisors


This is a program to count the number of divisors for a number, but it is giving one less divisor than there actually is for that number.

#include <stdio.h>

int i = 20;
int divisor;
int total;

int main()
{
    for (divisor = 1; divisor <= i; divisor++)
    {
        if ((i % divisor == 0) && (i != divisor))
        {
            total = total++;
        }
    }
    printf("%d %d\n", i, total);
    return 0;
}

The number 20 has 6 divisors, but the program says that there are 5 divisors.


Solution

  • && (i != divisor)
    

    means that 20 won't be considered a divisor. If you want it to be considered, ditch that bit of code, and you'll get the whole set, {1, 2, 4, 5, 10, 20}.

    Even if you didn't want the number counted as a divisor, you could still ditch that code and just use < instead of <= in the for statement.

    And:

    total = total++;
    

    is totally unnecessary. It may even be undefined, I'm just too lazy to check at the moment and it's not important since nobody writes code like that for long :-)

    Use either:

    total = total + 1;
    

    or (better):

    total++;