Perfect number program in Python

Perfect number in Python

According to number theory, a limb of pure mathematics that deals with integers, a Perfect Number can be defined as a positive integer whose value is equivalent to the sum of its proper positive divisors, excluding the number itself (alternatively known as aliquot sum).

An example of a perfect number is the number 6, the first perfect number in the series. The numbers 1, 2, and 3 are its proper divisors, and the sum of all three proper divisors gives us the original number, which makes it a perfect number.

In this tutorial, we will discuss different ways to check whether a number is a perfect number in python.

Use the Simple iteration method to check whether a given number is a perfect number.

In the Simple iteration method, we iterate through all the numbers from 1 to the desired number x to check if that specific number is a proper divisor. The code returns a true value if the sum of all the proper divisors is found to be equal to the number x, otherwise, it returns false.

The following code implements the Simple iteration method to check whether a given number is a perfect number.

Output:

True

Explanation

  • Created a function, which takes in the value x, which is the original number that needs to be evaluated.
  • We create a loop or an iteration for generating the numbers from 1 to x, and then the if statement to check if the number divided by the variable i gives no remainder and is a proper divisor.
  • All the proper divisors that are found out by the iteration are added together, and if the sum of proper divisors is equivalent to the original number x, then it is a perfect number. The result is then printed.

Use the square root method to check whether a given number is a perfect number.

Another method, which is arguably the more efficient method out of the two, is the square root method.

In this method, we iterate through all the numbers up until the square root of n is encountered. The basic concept is to add both i and x/i to the sum s, if the number i divides the original number x which is to be checked for a perfect number.

The following code implements the square root method to check whether a given number is a perfect number.

Output:

True

Time complexity of an algorithm or a code can be defined as the total time that is essential for the program to run till its execution gets terminated. The first method has the time complexity of O(n), whereas the second method, which is the square root method, has the time complexity O(n^1/2).

Therefore, due to this difference in time complexities between the two methods, the second (square root) method is considered to be much more efficient than the simple iteration method.

That’s all about Perfect number in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *