Joseph Jude

Swift Challenge 004: Factorial of n

2015.12.22 / code / swift /

Write a program to compute factorial of a number.

Challenge: Write a program to compute factorial of a number.

Logic: Factorial of n is a product of all positive integers less than or equal to n. Use recursion to calculate product.

Code:

func factorial(n: Int) -> Int {
  if n == 1 {
    return 1
  } else {
    return n * factorial(n - 1)
  }
}

print(factorial(5))

Teaches:

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.


Share this post on

Twitter | | |