Recursive Function: Factorial
Part of the Logic & Flow section of Coddy's Dart journey — lesson 49 of 65.
The factorial of a number is a classic mathematical operation that's perfect for demonstrating recursion. The factorial of a positive integer n (written as n!) is the product of all positive integers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
What makes factorial ideal for recursion is that it naturally breaks down into smaller, identical problems. To calculate 5!, you can think of it as 5 × 4!. And 4! is just 4 × 3!, and so on. This pattern continues until you reach 1!, which equals 1.
int factorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive step
}The base case stops the recursion when n <= 1, returning 1. The recursive step multiplies the current number by the factorial of the next smaller number. When you call factorial(5), it returns 5 * factorial(4), which returns 5 * 4 * factorial(3), and so on until it reaches the base case.
This approach demonstrates how recursion elegantly solves problems by reducing them to simpler versions of the same problem, making complex calculations feel natural and intuitive.
Challenge
EasyCreate a program that calculates factorials for multiple numbers using recursion. Your program will demonstrate the recursive factorial function by processing a list of numbers and computing their factorials.
- Read a string input containing numbers separated by commas (e.g.,
"3,5,0,7") - Split the input string into individual numbers and convert each to an integer
- Create a recursive function called
factorialthat takes an integer parametern - The
factorialfunction should implement the following logic: - Base case: If
nis less than or equal to 1, return 1 - Recursive step: Return
nmultiplied byfactorial(n - 1) - For each number in the input list, calculate its factorial using your recursive function
- Display the results showing each number and its corresponding factorial
- Calculate and display the sum of all the factorial results
For example, if the input is "4,3,2", your program should output:
Factorial Calculator
====================
Processing numbers: [4, 3, 2]
====================
Factorial Results:
4! = 24
3! = 6
2! = 2
====================
Sum of all factorials: 32
Calculation completed successfullyIf the input is "5,0,1", your program should output:
Factorial Calculator
====================
Processing numbers: [5, 0, 1]
====================
Factorial Results:
5! = 120
0! = 1
1! = 1
====================
Sum of all factorials: 122
Calculation completed successfullyIf the input is "6", your program should output:
Factorial Calculator
====================
Processing numbers: [6]
====================
Factorial Results:
6! = 720
====================
Sum of all factorials: 720
Calculation completed successfullyYour program must implement the recursive factorial function that calls itself with decremented values until it reaches the base case. The function should demonstrate how recursion breaks down the factorial calculation into smaller, identical subproblems. Use string interpolation to format the factorial results as "$n! = $result". Remember that 0! equals 1 by mathematical definition, which your base case should handle correctly.
Cheat sheet
The factorial of a positive integer n (written as n!) is the product of all positive integers from 1 to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
Factorial is ideal for recursion because it breaks down into smaller, identical problems: 5! = 5 × 4!, and 4! = 4 × 3!, continuing until reaching 1! = 1.
int factorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive step
}The base case stops recursion when n <= 1, returning 1. The recursive step multiplies the current number by the factorial of the next smaller number.
Try it yourself
import 'dart:io';
// TODO: Create your recursive factorial function here
void main() {
// Read input string containing comma-separated numbers
String? input = stdin.readLineSync();
// Split the input and convert to integers
List<int> numbers = input!.split(',').map((str) => int.parse(str.trim())).toList();
// TODO: Write your code below to:
// 1. Process each number using your factorial function
// 2. Calculate the sum of all factorials
// 3. Display the results in the required format
print("Factorial Calculator");
print("====================");
print("Processing numbers: $numbers");
print("====================");
print("Factorial Results:");
// TODO: Calculate and display factorial results here
print("====================");
// TODO: Display sum of all factorials
print("Calculation completed successfully");
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update7Advanced Functions
Anonymous FunctionsPassing Functions as ArgumentsUnderstanding ClosuresIntroduction to RecursionRecursive Function: CountdownRecursive Function: FactorialRecap - List Processor2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List