Home > Software design >  Find the sum of all the factors of a number n, excluding 1 and n
Find the sum of all the factors of a number n, excluding 1 and n

Time:10-05

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.

CodePudding user response:

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)
  • Related