1

I'm writing a program that finds perfect numbers. Having read about these perfect numbers I came across a list of them: List of perfect numbers. At the moment the output is:

28         // perfect
496        // perfect
8128       // perfect
130816     // not perfect
2096128    // not perfect
33550336   // perfect

I decided to create array and put it with numbers, which divide the number wholly (without the rest). So I will be able to verify if it is a perfect number or not by adding all elements of the array. But app crashes and I cannot understand why:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned long number;
    unsigned long arr2[100] = {0};
    int k = 0;

    for ( number = 0; number <= 130816; number++ )
        if ( 130816 % number == 0 )
            arr2[k++] = number;

    for ( k = 0; k < 100; k++ )
        printf("%lu", arr2[k]);

    return 0;
}
false
  • 10,264
  • 13
  • 101
  • 209
yulian
  • 1,601
  • 3
  • 21
  • 49

2 Answers2

5

You are doing modulus zero here:

if ( 130816 % number == 0 )

which is undefined behavior. If you start your for loop at 1 instead it should fix that issue. However, since N % 1 == 0 for all N, you probably need to start at 2.

From the C99 standard, 6.5.5 /5 (unchanged in C11):

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
  • @paxdiablo You are right, I forgot to remove that statement, I amended my answer. – Shafik Yaghmour Jun 06 '13 at 01:50
  • And a +1 for that :-) I also added the C11 stuff since that's now the "current" standard. And, actually, I think you may want to start at 2, not 1. `N%1` is zero for all `N`. – paxdiablo Jun 06 '13 at 01:57
2

You are dividing by zero when number=0;

138816 % number involves division and a remainder.

jim mcnamara
  • 16,005
  • 2
  • 34
  • 51