Write a loop that calculates 12-factorial.
Note: Although the problem asks specifically only for the value of 12-factorial, I’ve decided to write a slightly more generic loop in a function to pratice my R skills.
get_factorial <- function(n = 0) {
# Ideally the code to confirm that n is an integer would go here.
# Since it is not directly requested by the problem, assuming n is integer.
# Check that n is non-negative
if (n < 0) return(-1)
# Return 1 if n is zero
if (n == 0) return(1)
# Loop to calculate factorial
my_factorial <- 1
for (i in 1:n) {
my_factorial <- my_factorial * i
}
return(my_factorial)
}
get_factorial(12)
## [1] 479001600
Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
five_vector <- c(seq.int(20, 50, by = 5))
five_vector
## [1] 20 25 30 35 40 45 50
Note: I believe c() is unnecessary, but I do not have a feel for how explicit does one need to be in R yet.
Create the function “factorial” 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.
Quadratic equation: \(ax^2 + bx + c = 0\)
Solution: \(x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}\)
quadratic <- function(a, b, c) {
# Check that the equation is quadratic.
if (a == 0) {
return("Equation is not quadratic")
}
delta <- (b^2 - 4 * a * c)
if (delta > 0) {
# Two real solutions
solution1 <- (-b + sqrt(delta)) / (2 * a)
solution2 <- (-b - sqrt(delta)) / (2 * a)
return(sprintf("Equation has two real solutions: %s and %s", solution1, solution2))
} else if (delta == 0) {
# One real solution
solution1 <- -b / (2 * a)
return(sprintf("Equation has only one solution: %s", solution1))
} else {
# Two complex solutions
solution1 <- complex(real = -b / (2 * a), imaginary = sqrt(-delta) / (2 * a))
solution2 <- complex(real = -b / (2 * a), imaginary = - sqrt(-delta) / (2 * a))
return(sprintf("Equation has two complex solutions: %s and %s", solution1, solution2))
}
}
quadratic(1, -1, -2)
## [1] "Equation has two real solutions: 2 and -1"
quadratic(1, 2, 1)
## [1] "Equation has only one solution: -1"
quadratic(0, 1, 1)
## [1] "Equation is not quadratic"
quadratic(5, 7, -11)
## [1] "Equation has two real solutions: 0.940121946685673 and -2.34012194668567"
quadratic(1, 2, 2)
## [1] "Equation has two complex solutions: -1+1i and -1-1i"