82.2k views
0 votes
Write a recursive function that has a single parameter "n" and multiplies all the values from 1 * 2 * 3 * ... * n together. For example, if n = 5, 1 * 2 * 3 * 4 * 5 = 120.

1 Answer

1 vote

In Rust:

fn main() {

let n = 20;

println!("Factorial of {n}: {}", factorial_recursive(n));

}

fn factorial_recursive(n: u128) -> u128 {

if n == 1 {

1

} else {

n * factorial_recursive(n - 1)

}

}

In Python:

factorial_recursive = lambda n: 1 if n == 1 else n * factorial_recursive(n-1)

print(factorial_recursive(5))

User Gergely Toth
by
8.2k points

No related questions found