1- Question 1: Write a loop that calculate 12-factorial
#Iniatialize the factorial variable
factorial <- 1
# Use a for loop to calculate the factorial
for (i in 1:12) {
factorial <- factorial * i
}
#Print the result
factorial
## [1] 479001600
2- Question 2: Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
#Create a sequence using the seq() function
Num_vector_20_to_50 <- seq(20,50, by=5)
#Print result
Num_vector_20_to_50
## [1] 20 25 30 35 40 45 50
3- Question 3: Create the function “quad” that takes a trio of input numbers a, b, and c and solve the quadratic equation. The function should print as output the two solutions. Please run and test your answer for (1,2,1), (1,6,5) and (1,1,1).
# Function to solve the quadratic equation
quad <- function(a, b, c) {
# Calculate the discriminant
discriminant <- b^2 - 4 * a * c
# Check if the discriminant is positive, zero, or negative
if (discriminant > 0) {
# Two real and distinct solutions
solution1 <- (-b + sqrt(discriminant)) / (2 * a)
solution2 <- (-b - sqrt(discriminant)) / (2 * a)
cat("Two real and distinct solutions:\n")
cat("Solution X1:", solution1, "\n")
cat("Solution X2:", solution2, "\n")
} else if (discriminant == 0) {
# One real solution
solution <- -b / (2 * a)
cat("One real solution:\n")
cat("Solution:", solution, "\n")
} else {
# Negative discriminant. Complex solutions (imaginary roots)
cat("This function has no real roots\n")
}
}
Let’s test the quad function with inputs (1,2,1), (1,6,5) and (1,1,1).
#Test 1:
quad(1, 2, 1)
## One real solution:
## Solution: -1
#Test 2:
quad(1, 6, 5)
## Two real and distinct solutions:
## Solution X1: -1
## Solution X2: -5
#Test 3
quad(1, 1, 1)
## This function has no real roots