Created
April 10, 2018 11:07
-
-
Save victor-iyi/dbcedd88567d3921ce87b7b7c46fe4b8 to your computer and use it in GitHub Desktop.
A program to determine if a number is a perfect number.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| A program to determine if a number is a perfect number. | |
| """ | |
| def is_perfect_number(n): | |
| """Determines if a given number is a perfect number. | |
| Any number can be perfect number, if the sum of its | |
| positive divisors excluding the number itself is equal | |
| to that number. | |
| For example, 6 is a perfect number because 6 is divisible | |
| by 1, 2, 3 and 6. So, the sum of these values are: 1+2+3 = 6. | |
| === Parameters === | |
| n: int | |
| The number to we want to determine if it's | |
| a perfect number or not. | |
| === Return === | |
| bool: True|False | |
| If the number is a perfect number, it returns | |
| True otherwise we return False. | |
| """ | |
| # Initial value of total | |
| total = 0 | |
| for i in range(1, n): | |
| # Add the sum of n's multiple or the sum of | |
| # numbers that are "perfectly divisible by i". | |
| if n % i == 0: | |
| # Add the multiple to total. | |
| total += i | |
| # Don't search further if the sum > number. | |
| if total > n: | |
| break | |
| # Logic: `sum == number ? perfect : imperfect`. | |
| return True if total == n else False | |
| def main(): | |
| # We're dealing with postive integers here... | |
| number = abs(int(input('Enter a +ve integer: '))) | |
| # Call the function to determine if `number` is a | |
| # perfect number. | |
| ans = is_perfect_number(number) | |
| # Log appropriate message to the output stream. | |
| if ans: | |
| print('{} is a perfect number!'.format(number)) | |
| else: | |
| print('{} is not a perfect number!'.format(number)) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment