简体   繁体   中英

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!

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

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.

@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])

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM