+ 3

How to display all perfect numbers between 1 to 1000 along with their factors?

18th Aug 2016, 5:39 AM
Zafirah Mohamed iqbal
Zafirah Mohamed iqbal - avatar
2 odpowiedzi
+ 2
Perfect number is a positive integer that is equal to the sum of its proper divisors, excluding the number itself. For example: 6 is a perfect number since divisor of 6 are 1,2,3 and the sum of 1,2,3 equal 6. #include <iostream> void perfect(int); int main() { int number; for (number=1; number <= 1000 ; number++) perfect(number); return 0; } void perfect(int number) { int total = 0; for (int i = 1; i < number; i++) { if (number % i == 0) total += i; } if (number == total) { for (int x = 1; x < number; x++) { if (number % x == 0) std::cout << x << " + "; } std::cout << " = " << number << std::endl; } } It will print: 1+2+3 = 6 1+2+4+14 = 28 1+2+4+8+16+31+62+124+248= 496
18th Aug 2016, 7:23 AM
0xfz13
0
Thanks a lot :)
22nd Aug 2016, 6:05 AM
Zafirah Mohamed iqbal
Zafirah Mohamed iqbal - avatar