Write your question here.
So I have to write a program that asks the user to enter a range of 2 numbers and print out if there are perfect numbers in that range. if there are no perfect numbers in the given range print out "there are no perfect numbers found." using 2 loops and a function to test if true or false.
I cannot get it to print out if there are no perfect numbers correctly. The different expressions of IF statements i have tried either print out "there are no perfect numbers" about 100 times or it does not print anything out at all. Do the loops need to be inside the function so they are not run through multiple times?
bool found = false;
for (num = startVal; num <= endVal; num++)
if (is_perfect(num)){
cout << num << " is a perfect number." << endl;
found = true;
}
if (not found)
cout << "There are no perfect numbers between " << startVal << " and " << endVal << endl;
print out if there are perfect numbers in that range.
The task does not say: "print the perfect numbers".
There either are perfect numbers in range or not. Yes or no.
Therefore, you can stop the search when you find the first perfect number:
1 2 3 4 5 6 7 8 9 10 11 12
bool found = false;
for ( num = startVal; num <= endVal; ++num ) {
if ( is_perfect(num) ) {
found = true;
break;
}
}
if (found) {
cout << "There are\n";
} else {
cout << "None\n";
}
Apologies for the misinformation in the task,
I do need the program to print out the perfect numbers in the given range, not just say "There are perfect numbers"
I was able to get the program to stop printing "there are no perfect numbers" multiple times but it seems that it is still running through the loop and printing "there are no perfect numbers" AND the perfect numbers in the range. Do i need to change the loops from for to another form? (I have to use 2 loops as a requirement)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
bool found = false;
for (num = startVal; num <= endVal; num++)
{
sum = 0;
for (newNum = 1; newNum < num; newNum++)
{
if (isAfactor(num, newNum)) {
sum = sum + newNum;
found = true;
}
}
if (sum == num)
{
cout << num << " is a perfect number." << endl;
}
if (not found)
cout << "There are no perfect numebrs between " << startVal << " and " << endVal << endl;
}
bool is_perfect( int X )
{
int sum = 0;
for (int newNum = 1; newNum < X; newNum++)
{
if ( isAfactor(X, newNum) )
{
sum = sum + newNum;
}
}
return (sum == X);
}