Perfect number program?

I'm writing a program to find all of the perfect numbers between 1 and 650. So I used a couple loops but the only output I'm getting is -
"0 is a perfect number"
Any help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main()
{
    int x = 0;

    while(x <= 650)                
    {
      int sum = 0;

        for(int y = 0; y < x; ++y)
       {

             if(x % y == 0)
             {
              sum = sum + y;
             }
       }    
      
       if(sum == x)
       {
       cout << x << " is a perfect number\n";
       }
      
      ++x;          
              
    }         
Last edited on
You cannot divide (or modulus) a number with zero.
My program is warning me of division by zero.

You should guard your code against cases like this :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int x = 0;

    while(x <= 650)                
    {
      int sum = 0;

        for(int y = 0; y < x; ++y)
       {
			if(y != 0) // <==
			{
				 if(x % y == 0)
				 {
				  sum = sum + y;
				 }
			}
       }    
      
       if(sum == x)
       {
       cout << x << " is a perfect number\n";
       }
      
      ++x;          
              
    }   

}
Ah! I knew it was a simple problem. Always is. I just initialized x & y as 1 instead. Thanks dude!
Topic archived. No new replies allowed.