# Function to calculate factorial using recursion
factorial <- function(n) {
if (n == 0) {
return(1) # Base case: factorial of 0 is 1
} else {
return(n * factorial(n - 1)) # Recursive case
}
}
# Check if a command-line argument is provided
if (length(commandArgs(trailingOnly = TRUE)) > 0) {
# Get the first command-line argument as a character
num_text <- commandArgs(trailingOnly = TRUE)[1]
# Check if the input is a valid non-negative integer
if (grepl("^[0-9]+$", num_text)) {
num <- as.integer(num_text)
if (num >= 0) {
result <- factorial(num)
cat("Factorial of", num, "is", result, "\n")
} else {
cat("Factorial is not defined for negative
numbers.\n")
}
} else {
cat("Invalid input. Please enter a non-negative
integer.\n")
}
} else {
cat("Usage: Rscript script_name.R <non-negative
integer>\n")
}
0 Comments