PDA

Click to See Complete Forum and Search --> : Logic problem with


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;
}

parksie
Nov 5th, 2000, 11:31 AM
No idea about the algorithm, but to format code enclose it in tags.

Negative0
Nov 16th, 2000, 02:53 PM
Try This for the top part of the algorithm:

#include <iostream.h>
#include <math.h>
int main()
{
for (int i=2; i<1000; i++)
{
int sumDiv = 0;
for (int d=1; d<pow(i,.5); d++)
{
if ( (i%d)==0)
{
if (d!=1)
sumDiv+=(i/d);
sumDiv+=d; //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 << i << endl;

}

}

You were adding the number(i) to sumDiv when you should have been adding d. I also optimized the code a little by only going to the square root of the number and taking both the numbers from the product.

[Edited by Negative0 on 11-16-2000 at 04:08 PM]