Colora
Nov 5th, 2000, 08:41 AM
I'm using Visual C++ 6.0. The following is the code supposed to display all "perfect numbers" up to 1000, and also display their divisors. The given definition of a perfect number is: Any number whose divisors add up to that number (not including itself). The number 6 is an example - its divisors are 1, 2, and 3. And 1+2+3=6.
It's giving me prime numbers only (I'll use this for my next assignment, which is to display prime numbers!). I can't find the error in the logic, I've tweaked it a few different ways. There are no compile errors, so at least I know I got the syntax right this time.
Here's the code (I can't get the boards to accept the formatting so it'll all line up on the left):
#include <iostream.h>
int main()
{
for (int i=2; i<1000; i++) { //use i as counter, start it at 2. Go up to 1000 by 1's.
int sumDiv = 0;{ //start sumDiv with 0 value.
for (int d=1; d<i; d++){ //use d as divisor counter, start at 1. Increase by
//1's as long as its value is less than i.
if ( (i%d)==0) //if divisor, divided by i, results in no remainder,
sumDiv+=i; //then add the divisor value to sumDiv variable.
}
if (sumDiv==i){ //if sumDiv has same value as i, then print
cout<<i<<" is a perfect number!"<<endl; //the statement to the left
cout<<endl;
}
}
cout<<"Proper Divisors"<<endl;
for (int d=1; d<i; d++){ //begins loop to set up output of divisors
if ( (i%d)==0){ //mods to check if divisor is real divisor of i
if (i==1)
cout<<d<<", ";
}
}
cout<<"are the proper divisors!"<<endl<<endl;
}
cout<<endl;
return 0;
}
It's giving me prime numbers only (I'll use this for my next assignment, which is to display prime numbers!). I can't find the error in the logic, I've tweaked it a few different ways. There are no compile errors, so at least I know I got the syntax right this time.
Here's the code (I can't get the boards to accept the formatting so it'll all line up on the left):
#include <iostream.h>
int main()
{
for (int i=2; i<1000; i++) { //use i as counter, start it at 2. Go up to 1000 by 1's.
int sumDiv = 0;{ //start sumDiv with 0 value.
for (int d=1; d<i; d++){ //use d as divisor counter, start at 1. Increase by
//1's as long as its value is less than i.
if ( (i%d)==0) //if divisor, divided by i, results in no remainder,
sumDiv+=i; //then add the divisor value to sumDiv variable.
}
if (sumDiv==i){ //if sumDiv has same value as i, then print
cout<<i<<" is a perfect number!"<<endl; //the statement to the left
cout<<endl;
}
}
cout<<"Proper Divisors"<<endl;
for (int d=1; d<i; d++){ //begins loop to set up output of divisors
if ( (i%d)==0){ //mods to check if divisor is real divisor of i
if (i==1)
cout<<d<<", ";
}
}
cout<<"are the proper divisors!"<<endl<<endl;
}
cout<<endl;
return 0;
}