Created
September 8, 2021 12:41
-
-
Save Kimjunkuk/b1f608aec3b57c42f23956f9311987e2 to your computer and use it in GitHub Desktop.
4. Question 4 Fill in the empty function so that it returns the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sum_divisors(n): | |
# Return the sum of all divisors of n, not including n | |
i = 1 | |
sum = 0 | |
while i < n: | |
if n % i == 0: | |
sum += i | |
i +=1 | |
else: | |
i+=1 | |
return sum | |
print(sum_divisors(0)) | |
# 0 | |
print(sum_divisors(3)) # Should sum of 1 | |
# 1 | |
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 | |
# 55 | |
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 | |
# 114 | |
print(is_power_of_two(1)) # Should be True | |
print(is_power_of_two(8)) # Should be True | |
print(is_power_of_two(9)) # Should be False | |
# DO NOT DELETE THIS COMMENT |
def sum_divisors(number):
# Initialize the appropriate variables
divisor = 1
total = 0
# Avoid dividing by 0 and negative numbers
# in the while loop by exiting the function
# if "number" is less than one
if number < 1:
return 0
# Complete the while loop
while divisor < number :
if number % divisor == 0:
total += divisor
# Increment the correct variable
divisor += 1
# Return the correct variable
return total
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
def sum_divisors(n):
if n == 0:
return 0
i = 1
sum = 0
while i < n:
if n % i == 0:
sum +=i
i +=1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0))
0
print(sum_divisors(3)) # Should sum of 1
1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
114