简体   繁体   中英

I want to compute the sum of first N even numbers based on the user input N using recursive function

I want to compute the sum of first N even numbers based on the user input N using recursive function.

For example:

Sample Input N: 5

Sample Output: 2 + 4 + 6 + 8 + 10 = 30

I did my code in 2 ways but both of them gave wrong outputs. I'm doing something wrong in the function part sorting number in the loop. So I need some help!

n = int(input("Enter a nmuber: "))
for i in range(1,n+1):
   for d in range(0,i+1,2):
       print(d)
   
n = int(input("Enter a number: "))
def get_even(n):
    for i in range(1,n+1,2):
        d += i
        print(d)

You can use the following.

Code

def sum_even(n):
    # Base case
    if n <= 1:
        return 0
    
    if n % 2:
        # odd n
        return sum_even(n - 1)     # sum from next smaller even
    else:
        # even n
        return n + sum_even(n - 2) # current plus sum from next smaller even

# Usage
n = int(input('Enter a nmuber: '))
print(sum_even(n)) 

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