Sunday, February 25, 2018

Python Program : To check for perfect integer

A positive integer n is said to be perfect if the sum of the factors of n, other than n itself, add up to n. For instance 6 is perfect since the factors of 6 are {1,2,3,6} and 1+2+3=6. Likewise, 28 is perfect because the factors of 28 are {1,2,4,7,14,28} and 1+2+4+7+14=28.

Write a Python function perfect(n) that takes a positive integer argument and returns True if the integer is perfect, and False otherwise.

Here are some examples to show how your function should work.


>>> perfect(6)
True
>>> perfect(12)
False
 
 
def perfect(n):
  factors_of_n=[]
  sum=0
  for i in range(1,n+1):
    if n%i==0:
      factors_of_n = factors_of_n + [i]
  for j in factors_of_n[0:-1]:
    sum=sum + j
  return(sum==n)
 
Thanks
Happy Programming ! 

1 comment:

  1. This article is a great article that I have seen in my python programming career so far, Its helps me a lot in this type of To check for perfect integer, and will continue to do so in the future.

    hire python developers in US

    ReplyDelete

Query for finding high dividend paying stocks

 Post the following query in Screen.in, to get list of high dividend yield stocks: Dividend yield > 6 AND Dividend last year > 1000 AN...