Nested for loop python (Summation/Math)

Viewed 803

My professor gave me rather unclear descriptions for some assignments with summation. I'm just wondering if I've got the right idea using nested for loops or if I'm way off? I've posted an image of said assignment below.

Assignment

def c(n):
    sum = 0
    for i in range(1, n+1):
        for j in range(1, n+1):
            sum = sum + i*j

    return sum
3 Answers

There is no need for loops here:

def c(n):
    return (n**2 + n)**2 / 4

This is equal to

1*(1+2+....+n) + 2*(1+2+....+n) + 3*(1+2+.....+n)+.....+n*(1+2+....n)

which is equal to

(1+2+....+n)*(1+2+.....+n) 

which is:

square of sum of 1 to n = (n(n+1)/2)**2

Someone probably stumbled upon here looking for how to use brute force nested for loops to find if two elements in an array equal a given sum. If so then this is your lucky day!

array2 = [1, 2, 4, 4]
sum_two = 8  

def two_equals_sum(array, sum):
  for i in range(len(array)-1):
    for j in range(i+1, len(array)):
      if array[i]+array[j]==sum:
        return print(f"{array[i]} + {array[j]} = {sum}!!!!")

  return print(f"There is no combination of numbers in array what equal {sum}")
two_equals_sum(array2,sum_two)

This will return 4+4=8. Hope this helped someone!

Related