Let the function O(n) denote the sum of natural numbers, i, less than or equal to n. However, this function has one trick - if the number to be added, i, is a power of 2, then instead of adding we subtract the number.
Find O(4)+O(5)+O(6)+...+O(10000)
function written in Python:
def OhSum(a, b):
exponent = 0
powersOfTwo = [] # make a list [0, 1, 2, 4, 8, ...]
OhList = [] # make a list [0, O(1), O(2), O(3), ...]
OhList.append(0) # now OhList[0] = 0
while b+1 > 2**exponent:
powersOfTwo.append(2**exponent)
exponent += 1
for i in range(1, b+1):
if i in powersOfTwo:
OhList.append(OhList[i-1] - i)
else:
OhList.append(OhList[i-1] + i)
mySum = 0
for i in range(a, b+1):
mySum = mySum + OhList[i]
return format(mySum, ',')
-------------------------
OhSum(4, 10000)
166,567,934,208
|
Posted by Larry
on 2019-10-14 18:00:07 |