Ruby - Find the Factorial of a Number

1. Introduction

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It's denoted as n! and has essential applications in mathematics, especially in permutations and combinations. In this post, we'll walk through a Ruby program to find the factorial of a given number.

2. Program Steps

1. Initialize your Ruby environment.

2. Request the user to provide a non-negative integer.

3. Use a method to calculate the factorial of the given number.

4. Display the factorial to the user.

3. Code Program

# Prompt the user to enter a non-negative integer
puts "Enter a non-negative integer:"
number = gets.chomp.to_i
# Method to calculate factorial
def factorial(n)
  return 1 if n == 0
  n * factorial(n - 1)
end
# Calculating the factorial of the provided number
result = factorial(number)
# Displaying the factorial result
puts "The factorial of #{number} is: #{result}"

Output:

Enter a non-negative integer:
5
The factorial of 5 is: 120

Explanation:

1. puts: This command is used to display messages to the console, prompting the user for input.

2. gets: Used to obtain user input. By default, it captures the input as a string.

3. chomp: Applied to the string input to remove the newline character, which is appended when the user hits Enter.

4. to_i: Converts the string to an integer.

5. factorial(n): This is a recursive method. It keeps calling itself until n becomes zero. For n=0, it returns 1 (since 0! is 1). For any other number, it multiplies the number with the factorial of its preceding number.


Comments