← Recursion

Factorial

Easy
Python
def factorial(n):
    if n<=1: return 1
    return n*factorial(n-1)
Java
public int factorial(int n){
    if(n<=1) return 1;
    return n*factorial(n-1);
}

Key Insight

One of the most identical solutions. Just add types and semicolons for Java.

Python → Java Differences

  • Logic virtually identical
  • Java needs return type
  • Most similar Python-Java
Python
def factorial(n):
    if n<=1: return 1
    return n*factorial(n-1)
Java
public int factorial(int n){
    if(n<=1) return 1;
    return n*factorial(n-1);
}

Algorithm Steps

1. Base: n<=1 -> 1
2. Return n*factorial(n-1)