简体   繁体   中英

sum of squares of the first n odd numbers

I was given an assignment to find the sum of the squares of the first n odd numbers whereby n is given by the user.

The assignment was;

The script only takes one input, so do not
# include any input command below. The print commands below are already given.
# Do not alter the print commands. Do not add any other prints commands.

r = range(1, n + 1)         # prepare the range
result = 0                  # initialise the result
for k in r:                 # iterate over the range
    result = result + k     # update the result

  compute the sum of the squares of the first n odd numbers, and print it

This is what I have done so far;

r = range(1, n ** n, 2)         
result = 0                  
for k in r:                 
    result = result + k     

I know the range is wrong because when I ran it, I used 5 as n and I expected the answer to be 165 because the squares of the first 5 odd numbers is 165 but instead I got 144.

Please help

r = range(1, n + 1,2)
print r
result = 0                  
for k in r:                
result = result + k ** 2
print result

if you pass n=5 then it will print 35 because the range is 1,3,5 and during iteration it skip the step 2,4..you are considering like 1,3,5,7,9=165 but actual result will be 35 so instead of n=5 you can pass n= 7 so when you will pass n=7 then range will be [1, 3, 5, 7, 9] and output will be 165

We want to do iterate through odd numbers so if we want to do n odd numbers we need to go up to 2*n. For example, 5 odd numbers would be 1,3,5,7,9 and 2*5=10, but we only want every other number so we have the command r = range(1, n * 2, 2)

We then start with zero and add to it, hence result = 0

Now we iterate through our range (r) and add to our result the iterator squared, hence result = result = (k * k)

Overall we have:

r = range(1, n * 2, 2)
result = 0
for k in r:
    result = result + (k * k)
print result

n**n is n to the nth power. So with n=5 , your range is all the odd numbers between 1 and 3125. It should be odd numbers between 1 and 10.

r = range(1, n ** n, 2) 
#               ^ replace n**n by ...

You want to sum squares, so you should compute squares :

result = result + k
#                   ^ something is missing here

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