Write a loop that calculates 12 factorial
ans_1 = 1
for (j in 1:12)
ans_1 <- ans_1 * j
ans_1
## [1] 479001600
Show how to create a numeric vector that contains the sequence from 20 to 50 by 5
ans_2a <- 5 * 4:10
ans_2a
## [1] 20 25 30 35 40 45 50
ans_2b <- seq(20, 50, 5)
ans_2b
## [1] 20 25 30 35 40 45 50
Create the function “factorial” that takes a trio of input numbers a, b, and c and solves the quadratic equation. The function should print as output the two solutions.
# This function solves for the roots of the quadratic equation specified
# by the coefficients a, b and c, which are assumed to be real numbers:
# ax^2 + bx + c = 0
# The function handles several special cases:
# - a = 0: linear equation, so only 1 root
# - b^2 = 4ac: only 1 root
# - b^2 < 4ac: no real roots (only complex roots)
factorial <- function(a,b,c) {
if (a == 0)
paste("a=0, not a quadratic equation, only 1 root: ", - c / b)
else {
disc <- b ^ 2 - 4 * a * c # calc the discriminant
term1 <- - b / 2 / a # calc first term
if (disc == 0)
paste("b^2 = 4ac, only 1 root: ", term1)
else {
if (disc < 0)
paste("b^2 < 4ac, no real solution")
else {
term2 <- sqrt(disc) / 2 / a # calc second term
paste("2 real roots: ", term1 + term2, " and ", term1 - term2)
}
}
}
}
# Now try some examples
factorial(0, -2, 1)
## [1] "a=0, not a quadratic equation, only 1 root: 0.5"
factorial(1, -6, 9)
## [1] "b^2 = 4ac, only 1 root: 3"
factorial(1, 1, 1)
## [1] "b^2 < 4ac, no real solution"
factorial(2, 5, -3)
## [1] "2 real roots: 0.5 and -3"
factorial(5, pi, -2)
## [1] "2 real roots: 0.392024877772891 and -1.02034340849085"