简体   繁体   中英

without Loops to Sum Range of odd numbers

有什么方法可以从 1 到 n 求和奇数但没有任何循环,如果没有办法我如何通过快速算法创建它以在少于 n 个循环中完成此任务。

You can take advantage of the summation in an Arithmetic Series to sum the first n odd numbers (not the odd numbers from 0 to n )

a = 1 # from 1
n = 9999 # to n
d = 2 # and skip every even number
n = int((n - a) / d + 1) # locate the number of term for n
sum = int((n / 2) * (2 * a + (n - 1) * d))

Time complexity: O(1), no loop

reference: Summing an Arithmetic Series

edit: to fit case for even n , eg 10000

if n % 2 == 0:
    n = n - 1 # to eliminate the case 10000 and find range 1-9999

尝试这个 -

sum(range(1, n+1, 2))

你可以试试下面的,从 1 到 n 循环,步进 2

sum(range(1,n,2))

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