160k views
2 votes
Write a function that is passed in a positive integer, n, and sum up all the digits from 1 to n, doubling the even numbers. In other words, calculate and return the following sum. if n is odd: 1 (2 * 2) 3 (4 * 2) ... ((n - 1) * 2) n if n is even: 1 (2 * 2) 3 (4 * 2) ... (n - 1) (n* 2)

1 Answer

7 votes

Answer:

Written in Python

def sums(n):

total = 0

for i in range(1,n+1):

if i%2 == 0:

total = total + i*2

else:

total = total + i

return(total)

Explanation:

The function is written in Python

def sums(n):

This initializes total to 0

total = 0

This iterates through the integers that makes up n i.e. 1,2,3.....n

for i in range(1,n+1):

This checks if current digit is even

if i%2 == 0:

If yes, it adds the double of the digit

total = total + i*2

else:

If otherwise, it adds the digit

total = total + i

This prints the calculated sum or total

return(total)

To call the function from main, use the following:

print(sums(n))

Where n is a positive integer. i.e.
n \geq 1

User Fenkerbb
by
4.2k points