A
Archie
Hi, I'm a beginner to c++. I wrote a program that identifies perfect
numbers (up to about 8 digits). You enter a number and the program
determines whether it is a perfect number.
Definition of a perfect number: a number whose factors (excluding the
number itself) sum to equal the number.
The first four perfect numbers are 6, 28, 496, 8128.
So the program I wrote to identify perfect numbers works. Here it is,
excluding the beginning lines through int main() and the last line:
int x;
cout << "Enter a positive integer.\n";
cin >> x;
int sum = 0;
for(int i = 1; i <= x/2; ++i){
if(x % i == 0)
{
sum += i;
}
}
if(sum == x){
cout << x << " is a perfect number.\n";
} else {
cout << x << " is not a perfect number.\n";
}
But when I write a loop to get the program to identify the first n
perfect numbers, the program fails no matter how few numbers I ask
for. Here it is:
int x = 1;
int n;
cout << "Enter a positive integer.\n";
cin >> n;
int sum = 0;
while(n > 0){
for(int i = 1; i <= x/2; ++i){
if(x % i == 0)
{
sum += i;
}
}
if(sum == x){
cout << x ;
n--;
}
x++;
}
Apparently, this gives an infinite loop? Nothing happens on the screen
after you enter the integer n.
What's the problem?
Thanks in advance.
Archie
numbers (up to about 8 digits). You enter a number and the program
determines whether it is a perfect number.
Definition of a perfect number: a number whose factors (excluding the
number itself) sum to equal the number.
The first four perfect numbers are 6, 28, 496, 8128.
So the program I wrote to identify perfect numbers works. Here it is,
excluding the beginning lines through int main() and the last line:
int x;
cout << "Enter a positive integer.\n";
cin >> x;
int sum = 0;
for(int i = 1; i <= x/2; ++i){
if(x % i == 0)
{
sum += i;
}
}
if(sum == x){
cout << x << " is a perfect number.\n";
} else {
cout << x << " is not a perfect number.\n";
}
But when I write a loop to get the program to identify the first n
perfect numbers, the program fails no matter how few numbers I ask
for. Here it is:
int x = 1;
int n;
cout << "Enter a positive integer.\n";
cin >> n;
int sum = 0;
while(n > 0){
for(int i = 1; i <= x/2; ++i){
if(x % i == 0)
{
sum += i;
}
}
if(sum == x){
cout << x ;
n--;
}
x++;
}
Apparently, this gives an infinite loop? Nothing happens on the screen
after you enter the integer n.
What's the problem?
Thanks in advance.
Archie