Reputation: 155
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
Reputation: 57728
Oh, so many issues.
perfect_number
never changes. Did your compiler flag
this?bool
values to true
or false
.isAFactor
function to return (outer %
inner) == 0;
.isAFactor
with the expression
((outer % inner) == 0)
.Upvotes: 0
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
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