Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my program not printing perfect integers?

Tags:

c++

math

cout

I am new to C++ programming and have a problem with one of my programs

#include <iostream>
using namespace std;
bool IsPerfect(int n);

int main ()
{
  for(int i=1; i<100; i++){
    IsPerfect(i);
  }

  return 0;
}

bool IsPerfect(int n){
  int sum;
  for(int x=1; x<n; x++){
    if(n%x==0){
      sum+=x;
      return true;
      cout <<n;
    }
    else{
      return false;
    }
  }
}

I am trying to create a program that will list perfect numbers but I can't find the bug as to why it would not print.

like image 359
idude Avatar asked Dec 09 '25 00:12

idude


2 Answers

I see 3 issues:

  1. Your algorithm is wrong. Your loop terminates on the first time a number is evenly divisible by any factor (including 1). See Wikipedia for an explanation of the algorithm.
  2. You have an uninitialized variable with int sum; Also, you only ever write to it, you don't read it in a useful manner ever.
  3. You have unreachable code. Your cout << n; in the loop will never be hit.

Try the following corrected code:

#include <iostream>
#include <cassert>
using namespace std;

bool IsPerfect(int n)
{
        int sum = 1;
        for(int x = 2; x < n; ++x)
        {
                if(n % x == 0)
                        sum += x;
        }
        return sum == n;
}

int main ()
{
        for(int i=1; i<100; i++){
                if (IsPerfect(i))
                        cout << i << endl;
        }

        assert(IsPerfect(6));
        assert(IsPerfect(28));
        assert(IsPerfect(496));

        return 0;
}
like image 105
Nathan Ernst Avatar answered Dec 11 '25 13:12

Nathan Ernst


You have a return statement before you output statement here:

return true;
cout <<n;

you need to swap the order of these statements, you also probably want to add a comma or some other separator:

std::cout << n << ", " ;
return true;

I am not sure that is where you want to return from since you will exit the first time you enter that if statement, which will happen when x is 1.

like image 45
Shafik Yaghmour Avatar answered Dec 11 '25 12:12

Shafik Yaghmour