Files
30-seconds-of-code/snippets/factorial.md
Isabelle Viktoria Maciohsek cbc78ee450 Bake dates into snippets
2021-06-13 19:38:10 +03:00

610 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
factorial math,recursion,beginner 2018-01-27T07:29:56+02:00 2020-09-15T16:13:06+03:00

Calculates the factorial of a number.

  • Use recursion.
  • If num is less than or equal to 1, return 1.
  • Otherwise, return the product of num and the factorial of num - 1.
  • Throws an exception if num is a negative or a floating point number.
def factorial(num):
  if not ((num >= 0) and (num % 1 == 0)):
    raise Exception("Number can't be floating point or negative.")
  return 1 if num == 0 else num * factorial(num - 1)
factorial(6) # 720