n0de
n0de

Reputation: 155

C++ Perfect Number With Nested Loops Issue

What I am trying to do is search for a perfect number. A perfect number is a number that is the sum of all its divisors, such as 6 = 1+2+3.

Basically what I do here is ask for 2 numbers and find a perfect number between those two numbers. I have a function that tests for divisibility and 2 nested loops.

My issue is that I don't get any result. I've revised it & can't seem to find anything wrong. The compiler doesn't shoot out any errors.

What can be wrong?

#include <iostream>
using namespace std;

bool isAFactor(int, int);

int main()
{

int startval;
int endval;
int outer_loop;
int inner_loop;
int perfect_number = 0;

cout << "Enter Starting Number: ";
cin >> startval;
cout << "Enter Ending Number: ";
cin >> endval;

for(outer_loop = startval; outer_loop <= endval; outer_loop++)
{
    for(inner_loop = 1; inner_loop <= outer_loop; inner_loop++)
    {
        if (isAFactor(outer_loop, inner_loop) == true)
        {
            inner_loop += perfect_number;
        }
    }

if (perfect_number == outer_loop)
{
    cout << perfect_number << " is a perfect number." << endl;
}

else
{
    cout << "There is no perfect number." << endl;
}

}

system("PAUSE");
return 0;
}

bool isAFactor(int outer, int inner)
{
if (outer % inner == 0)
{
    return true;
}

else
{
    return false;
}

Upvotes: 0

Views: 2099

Answers (3)

Thomas Matthews
Thomas Matthews

Reputation: 57728

Oh, so many issues.

  1. The variable perfect_number never changes. Did your compiler flag this?
  2. The outer loop will be one more than the ending value when it exits; did you know this?
  3. You don't need to compare bool values to true or false.
  4. You could simplify the isAFactor function to return (outer % inner) == 0;.
  5. You could replace the call to isAFactor with the expression ((outer % inner) == 0).

Upvotes: 0

Rustam Kichinsky
Rustam Kichinsky

Reputation: 129

after the if statement:

cout << perfect_number;
cout << outer_loop;

if (perfect_number == outer_loop)
{
    cout << perfect_number << " is a perfect number." << endl;
}

and see what values they have

Updated:

What is the value of your endval? is 0?, and thats why the loop ends so early

Upvotes: 0

Steve Jessop
Steve Jessop

Reputation: 279325

inner_loop += perfect_number; should be perfect_number += inner_loop;.

There are other issues -- you need to reset perfect_number to zero in each outer loop, and you should presumably print the message "There is no perfect number." if none of the numbers in range is perfect, rather than printing it once for every number in range that is not perfect.

I'd advise that you rename perfect_number to sum_of_factors, outer_loop to candidate_perfect_number and inner_loop to candidate_factor, or similar.

Upvotes: 2

Related Questions