-3

Here is my program, which aims to show whether the input integer is a perfect number or not. It is required to use Boolean function and call it back in main function. However, after running the trial, there is no output. Can anyone help out this programming newbie...Thanks in advance for any help.

#include <iostream>
using namespace std;

bool perfect ( int num )
{
    int sum = 0, i = 1;
    while( i < num ) {
        if ( num % i == 0 ) {
            sum = sum + i;
            i++;
        }
    }

    if ( num == sum )
        return 1 ;
    else
        return 0 ;
}

int main()
{
    int num ;
    cin >> num ;

    if ( perfect ( num ) == 1 )
        cout << " YES " << endl ;
    else
        cout << " NO " << endl ;
}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Paulpaul
  • 11
  • 1
  • 1
  • 2
  • 2
    You should use your debugger to step through your code and see where it differs from what you expect. – chris Mar 04 '17 at 17:11
  • 2
    The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Mar 04 '17 at 17:12

2 Answers2

2

Let's look at your loop when num == 3 and i == 2.

int i = 1;
while( i < num ) {
    if ( num % i == 0 ) {
        sum = sum + i;
        i++;
    }
}
  1. i < num is 2 < 3 which is true, so we'll enter the while loop.
  2. num % i == 0 is 3 % 2 == 0 which is false, so we won't enter the conditional.
  3. We head back to the top of the while loop.
  4. i and num haven't changed, so this is an infinite loop.

You probably want something like:

bool perfect_number(int x) {
  int sum_of_divisors = 0;
  for (int divisor = 1; divisor < x; divisor++)
    if (x % divisor == 0)
      sum_of_divisors += divisor;
  return sum_of_divisors == x;
}

Which we can optimize into:

bool perfect_number(int x) {
    return x == 6 || x == 28 || x == 496 || x == 8128 || x == 33550336;
}
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Thank you for your help! I now understand where the problem is...I never thought of this problem... – Paulpaul Mar 05 '17 at 05:28
-1

Your function perfect(int) return a bool and not an integer, so if(perfect(num)) can be used directly. You could have used return type int for function perfect() to use 'if' condition as: if(perfect(num)==1)

Svenmarim
  • 3,633
  • 5
  • 24
  • 56
Neetu
  • 1