(Perfect Numbers) An integer is said to be a perfect number if the sum of its divisors, including 1 (but not the number itself), is equal to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3.
Write a function is Perfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. Print the divisors of each perfect number to confirm that the number is indeed perfect. Challenge the power of your computer by testing numbers much larger than 1000.
Solution:
Write a function is Perfect that determines whether parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. Print the divisors of each perfect number to confirm that the number is indeed perfect. Challenge the power of your computer by testing numbers much larger than 1000.
Solution:
#include <iostream> using std::cout; using std::cin; using std::endl; void perfect(int); int main() { for(int number = 1; number <= 1000; number++) { perfect(number); } return 0; } //perfect number function void perfect(int number) { int j = 0; for(int i = 1; i < number; i++) { if(number % i == 0) { j = j + i; } } if(number == j) { cout << "\nPerfect number is " << number << " and its divisors: "; for(int i = 1; i < number; i++) { if(number % i == 0) { cout << i << ", "; } } } }
Post A Comment:
0 comments: