I have to write a program involving multiple function, and im having a lot of trouble even starting it.
The assignment is the following:
A perfect number is one which is equal to the sum of its divisors (excluding itself). For example, 6 is a perfect number (the divisors of 6 are 1, 2, 3, 6; sum = 6).
Write a function sumdiv that accepts an integer and returns the sum of the divsors of the integer that was pass (excluding the integer itself). Thus a call of sumdiv(6) would return 6; a call to sumdiv(15) would return 9 (= 1 + 3 + 5).
I know this will involve at least one other function besides main, but im not sure how to set this up. How do I figure out the divisors of any integer I enter? And then how do I test to see if they add back to the original integer?
#include <iostream>
#include <cmath>
usingnamespace std;
int sumdiv (int i){
{
int sum = 0;
int n, i = 1;
for(i=1; i>n; i++){
for(n = 1; n<i; n++)
if (i%n==0)
sum+= n;}
return sum;
}
}
int main()
{
cout << sumdiv(6) << "\n\n";
return 0;
}
No more error messages but its still giving me the wrong output. I entered the number "6" into main, so the output should also be 6. But no matter what number I input, the output is always 0. Whats the problem?
First on style. It is legal to have only one statement on a loop body or in if-clause, but it is more clear to use a brace-block.
Second: 1 divides every number. There is no need to calculate it, unless input is less than 1.
Therefore:
1 2 3 4 5 6 7 8 9 10
// Returns sum of divisors of param i
// The param i must be greater than 0
int sumdiv ( int i ) {
int sum = 1;
for ( int n = 2; n < i; ++n ) {
if ( 0 == i % n ) {
sum += n;
}
return sum;
}