Implement a function amicable that takes a positive integer n. It returns the sm
ID: 667552 • Letter: I
Question
Implement a function amicable that takes a positive integer n. It returns the smallest amicable number greater than n.
Two different numbers are both amicable if the sum of the proper divisors of each is equal to the other. Any number that's part of such a pair is an amicable number.
Hint: You may want to create a separate function to sum proper divisors.
def amicable(n):
"""Return the smallest amicable number greater than positive integer n.
Every amicable number x has a buddy y different from x, such that
the sum of the proper divisors of x equals y, and
the sum of the proper divisors of y equals x.
For example, 220 and 284 are both amicable because
1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 is 284, and
1 + 2 + 4 + 71 + 142 is 220
>>> amicable(5)
220
>>> amicable(220)
284
>>> amicable(284)
1184
>>> r = amicable(5000)
>>> r
5020
"""
"*** YOUR CODE HERE ***"
Explanation / Answer
def amicable(n):
i = 1
while 1>0:
#print ("XX")
#print( n+i)
sum1 = sumOfDivisors(n+i)
#print ( sum1)
if sum1 != n+i:
sum2 = sumOfDivisors(sum1)
#print ( sum2)
#print(n+i,end="")
#x = input()
#print (sum1, end="")
#print (sum2)
if sum2 == n+i :
print ( n+i )
break
i += 1
def sumOfDivisors(n):
res = 1
cpy = n
#print( n )
i = 2
while i < n+1 :
sum = 1
#print ("Hey")
#print(i, end = " ")
if n%i == 0:
cnt = 1
while n%i == 0 :
sum += i**cnt
n = n/i
cnt += 1
#print (cnt, end = " ")
#print (sum)
res *= sum
i += 1
return res-cpy
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.