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

Question:

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:

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

Thanks in advance.

Asked By: metal

||

Answers:

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)
Answered By: JRose
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.