Exercises - Basic Programming Constructs

Please take care of following exercises.

  • Get sum of integers for a given range.

lb = 5
ub = 10

total = 0
for i in range(lb, ub+1):
    total += i
    
print(i)
# Complexity: o(n)
10
  • If you recollect your high school mathematics, there is a formula to get sum of integers for 1 to n. It is nothing but (n * (n + 1))/2. Using that we should be able to get sum of integers with in a given range between lower bound (lb) and upper bound (ub). It is nothing but

((ub * (ub + 1)) / 2) - (((lb - 1) * lb) / 2)

lb1 = lb - 1
res1 = lb1 * (lb1 + 1) / 2
print(int(res1))
10
res2 = ub * (ub + 1) / 2
print(int(res2))
55
print(int(res2 - res1))
# Complexity: o(1)
45
# o(1) is much better solution when compared to o(n)
  • Get sum of squares of integers for a given range using formula - for 2 to 4, it should be 29. You can google around to get the formula for sum of squares of integers for 1 to n.

  • Get sum of even numbers for a given range - for 5 to 10, it should 24.

  • Create a collection using [1, 6, 8, 3, 7, 2, 9] and get sum of even numbers. Answer should be 16.

  • Using the same collection get sum of numbers divisible by 3. Answer should be 18.