0

I'm not a very experienced programmer but I just wrote this in Python to try and find e, using the definition that e is the sum of 1/0! + 1/1! + 1/2! etc...

The problem I'm having is def factorial doesn't output an integer. I realize it wouldn't given how it's written but I'm not sure how I can make it. total is what I would want outputted as an int from def factorial.

e = 0

def factorial(m):
    n = m - 1
    total = 1
    if n > 0:
        total = m
    while n > 0:
        total = total * n
        n = n - 1

for w in range(0,100):
    s = factorial(w)
    e = e + ( 1 / s )

print(e)
8
  • 8
    gotta love this title...
    – Bitwise
    Apr 8, 2013 at 1:43
  • Use return, lol @Bitwise Apr 8, 2013 at 1:46
  • 1
    e is a real number. You would not want total to be an integer anyway I guess. Integers only represent natural numbers (including negatives). Apr 8, 2013 at 1:46
  • total is just a factorial, it absolutely should be int
    – User1
    Apr 8, 2013 at 1:48
  • Oh sorry... for some reason I thought 1/2! was supposed to be read as (1/2)!. Of course factorials of rational numbers don't make sense. I should go to sleep now... Apr 8, 2013 at 1:51

2 Answers 2

6
def factorial(m):
    n = m - 1
    total = 1
    if n > 0:
        total = m
    while n > 0:
        total = total * n
        n = n - 1
    return total

EDIT: The problem is that, in order to get information from factorial, you have to use a return statement. Anything after the return is evaluated, and used as the value of s in s = factorial(w).

2
  • It would be better if you explained what the problem was (even if it might be obvious for you and me). Apr 8, 2013 at 1:45
  • Lo siento. Added an explanation.
    – hatkirby
    Apr 8, 2013 at 1:47
2

The code by Feffernoose works. But to improve the performance in your case, you would better use the "yield" statement to build a iterable object.

e = 0
def factorial(m):
    assert(m>1)
    current = 0
    total = 1
    while current<=m:
        yield total
        current += 1
        total *= current

for w in factorial(100):
    e = e + ( 1 / w )
print(e)

Update: in the solution with "return", you approximately need O(n*n) time for the factorial value computation. But with "yield", you only need O(n).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.