Home > front end >  program that reads an integer, and prints all the perfect numbers
program that reads an integer, and prints all the perfect numbers

Time:11-10

int n;
int sum;
    
cout << "write a number";
cin >> n;

for (int i = 1; i < n; i  )
{
    sum = 0;
    for (int j = 1; j <= i; j  )
    {
        if (i % j == 0)
            sum = sum   j;
    }
    if (sum == i)
        cout << i<< endl;
}

Why do I always get 1 as a result? I couldn't understand the logic of it. When I change the second for loop and make it i/2, I get the correct result, but I couldn't understand how it worked.

input 1000
expected result = 6 28 496

CodePudding user response:

Remind about mathematics. Refer to wiki

In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself.

So, in your code, you are making sum of ALL divisors of i include itself. That's why you only get result 1.

You should change it simply.

for (int j = 1; j < i; j  )
  •  Tags:  
  • c
  • Related