Antonio
Antonio

Reputation: 87

Nested for loop python (Summation/Math)

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

Upvotes: 2

Views: 1406

Answers (3)

davidj
davidj

Reputation: 1

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!

Upvotes: 0

Gautham M
Gautham M

Reputation: 4935

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

Upvotes: 0

Jörg W Mittag
Jörg W Mittag

Reputation: 369430

There is no need for loops here:

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

Upvotes: 1

Related Questions