ok, so I feel a little stupid because I don’t know this, but a colleague asked, so I ask here: I wrote a python algorithm that solves his problem. if x> 0, add all numbers together from 1 to x.
def intsum(x): if x > 0: return x + intsum(x - 1) else: return 0 intsum(10) 55
first, what is the type of this equation, and what is the correct way to get this answer, since it is clearly easier to use any other method?
This is recursion, although for some reason you are marked as factorial.
In any case, the sum from 1 to n is also simple:
n * ( n + 1 ) / 2
(If you want, you can use a special case for negative values.)
, , - Concrete Mathematics: Foundation for Computer Science, , (., , wikipedia ).
, , fac(x) = fac(x - 1) + x, , , - 1 100 , 5050 : " , , 1 , 100, 101, , 2 -, 99, 101, , , 50 , 50 101, 5050". , , 6-; -).
fac(x) = fac(x - 1) + x
( ) , , , (N * (N+1)) / 2 ( , ; ).
(N * (N+1)) / 2
S = 1 + 2 + ... + (n-1) + n S = n + (n-1) + ... + 2 + 1 2S = (n+1) + (n+1) + ... + (n+1) + (n+1) ^ you'll note that there are n terms there. 2S = n(n+1) S = n(n+1)/2
, n.
n
Python, , , . .
sum()
>>> sum(range(11)) 55 >>> sum([2,4,6]) 12
, reduce()
reduce()
>>> import operator >>> reduce(operator.add, range(11)) 55
, , range(), 0 base. (n + 1), .
...
sum ( (10))!= 55
sum ( (11)) == 55
OP .
. , , , , 1 100. , .
, . .
Note that N + 1, N-1 + 2, N-2 + 3, etc. all add up with the same number, and about the same N / 2 copies (exactly N / 2, if N even).
What you have there is called an arithmetic sequence, and as suggested, you can calculate it directly without the overhead that may result from a recursion.
And I would say that this is homework, despite what you say.