Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the sum of all the factors of a number n, excluding 1 and n

So I have this piece of code so far:

def OfN(n):
  print("Factors of ",n,"= ", end="")
  factor = []
  for j in range(2, n + 1):
    if n % j == 0:
      print(j, end=" ")
      factor.append(j)
  sumN = sum(factor)
  print("\nSum of all factors = " + str(sumN))

  if sumN < n:
    return True
  else:
    return False

My problem is I don’t know how to exclude the number itself from the sums/printing. I excluded 1 by starting counting from 2. How would I exclude the number from appearing?

For example, if we use 5, this should happen:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>> OfN(5)
>>
>> Factors of 5 = 
>> Sum of all factors = 0
>> True

Thanks in advance.

>Solution :

Just remove the +1 in your range. This will iterate from 2 to n – 1, which will exclude n from the factors.

def OfN(n):
  print("Factors of ",n,"= ", end="")
  factor = []
  for j in range(2, n):
    if n % j == 0:
      print(j, end=" ")
      factor.append(j)
  sumN = sum(factor)
  print("\nSum of all factors = " + str(sumN))

  if sumN < n:
    return True
  else:
    return False

OfN(5)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading