Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Math equation of Python Algorithm?

ok so I am feeling a little stupid for not knowing this, but a coworker asked so I am asking here: I have written a python algorithm that solves his problem. given 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 this type of equation is this and what is the correct way to get this answer as it is clearly easier using some other method?

like image 973
Gabriel Avatar asked May 18 '10 23:05

Gabriel


1 Answers

This is recursion, though for some reason you're labeling it like it's factorial.

In any case, the sum from 1 to n is also simply:

n * ( n + 1 ) / 2

(You can special case it for negative values if you like.)

like image 89
Larry Avatar answered Sep 28 '22 01:09

Larry