Alyssie
Alyssie

Reputation: 145

How do I write a function function(n) that takes in an integer, and returns the sum of the first n even numbers using a while loop?

How do I write a function function(n) that takes in an integer, and returns the sum of the first n even numbers using a while loop? Example: function(3) returns 12 because the first three even numbers are 2, 4, 6.

My code:

def function(n):
        result = 0
        while i < 2*n+1:
                if not i%2==1:
                        result += i
        return result

However the result I get was "i" was not defined. I appreciate help and thanks!

Upvotes: 0

Views: 1530

Answers (4)

abhiarora
abhiarora

Reputation: 10430

You haven't defined variable i and aren't incrementing the i in your for loop and that's why you have an infinite loop.

The code should look like this:

def function(n):
    i = 0
    result = 0
    while i < 2 * n + 1:
        if not i % 2:
            result += i
        i += 1
    return result

However, the clean ways of doing this are given below:

# Time complexity of O(n)
def fun(n):
    result = 0
    for i in range(1, n + 1):
        result += 2*i
    return result

# Efficient as having time complexity of O(1)
def fun2(n):
    return n * (n + 1)

print(fun2(3))
print(fun(3))

You can use fun2 as it has time complexity of O(1). See this to learn more.

Upvotes: 2

jclark754
jclark754

Reputation: 1014

Less elegant than some of these fancy pants one-liners but wanted to add a while True answer:

def fn(num):
    vals, counter = 0, 0
    even_nums = []
    while True:
        if vals < num:
            counter += 2
            even_nums.append(counter)
            vals += 1
        else:
            return sum(even_nums)

Upvotes: 0

Guy
Guy

Reputation: 50809

@TreysenZobell answer explained the problem. Another one line solution is to use built-in sum()

def function(n):
    return sum([i for i in range(2 * n + 1) if i % 2 == 0])

Upvotes: 1

Treysen Zobell
Treysen Zobell

Reputation: 63

You forgot to declare i and increment it with each loop

def func(n):
   result = 0
   i = 0
   while i < 2*n+1:
      if i%2 == 0:
         result += i
      i += 1
   return result

Upvotes: 3

Related Questions