Search code examples
pythonmathfactorial

I have written this equation with for loop. anyone got any idea about other forms to write this equation?


equation : 1 + 1/2! + 1/3! + 1/4! ... + 1/n! --> (n < 10)

#define factorial

def fact(x):
    if x == 0:
        return 1
    else:
        return x * fact(x-1)

#---------Long way------------

#equation= 1 + 1/fact(2) + 1/fact(3) + 1/fact(4) + 1/fact(5) + 1/fact(6)+ 1/fact(7) + 
#1/fact(8)+ 1/fact(9) 
#print(equation)

#---------with for Loop-------

s = 1
for x in range (2,10) :
  s += (1/fact(x))
print(s)
 

#-----------------------------


Solution

  • If its always gonna be n < 10, then why compute factorial each time,

    s = 1
    y = 9*8*7*6*5*4*3*2
    j = 9
    while j >1:
      s += (1/y)
      y = y/j
      j = j-1
    print(s)
    

    Or compute factorial only for the n-th number and do the same as above.