-
February 16th, 2018, 09:06 PM
#1
Perfect number program
I am trying to get a program to print all the perfect numbers from 1-1000. It does not print any numbers to the console.
Code:
Code:
#include<iostream>
using namespace std;
int main()
{
int num = 1, adder = 1, numChecker = 0;
for(num = 1; num >= 1000; num++)
{
numChecker = 0;
for(adder = 1; adder > num; adder++)
{
if(num % adder == 0)
{
numChecker += adder;
}
}
if(num == numChecker)
{
cout << num << endl;
}
}
return 0;
}
Last edited by VictorN; February 17th, 2018 at 02:43 AM.
Reason: added CODE tags, brackets and indentations
-
February 17th, 2018, 02:40 AM
#2
Re: Perfect number program
Check the for-loops.
If for example you want the variable num to take values from 1 up to (and including) 1000 you should do,
Code:
for (num = 1; num <= 1000; num++)
Last edited by wolle; February 17th, 2018 at 02:59 AM.
-
February 17th, 2018, 02:47 AM
#3
Re: Perfect number program
Well, I have edited your code t make it readable.
Now you could see that it prints something only if num == numChecker.
So try to debug your code step-by-step to see what goes wrong or non-expected.
I'd also recommend you to begin testing with some more trivial diapasons like 1-5, 1-10, 1-20, etc.
Victor Nijegorodov
-
February 17th, 2018, 04:07 AM
#4
Re: Perfect number program
Also note that within the range of an int, there are no odd perfect numbers (indeed currently there are no known odd perfect numbers at all!). So the starting value for the outer for loop could be 2 and not 1 and the value could be incremented by 2 rather than 1 (to generate even numbers).
Note also that 1 is always a divisor of an integer - so need not be tried. So numchecker could be initialised to 1 and the starting value for the inner for loop could be 2 and not 1.
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|