Write a loop that calculates 12-factorial
x <- 12
f <- 1
for (i in 1:x){
f <- f*i
}
sprintf("My factorial: %d , Built in factorial: %d", f,factorial(x))
## [1] "My factorial: 479001600 , Built in factorial: 479001600"
Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
numeric_vector <- seq(20,50,5)
print(numeric_vector)
## [1] 20 25 30 35 40 45 50
Create the function “quadratic” 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 <- function(a,b,c){
x <- (b^2 - 4*a*c)
if (x > 0){
sol_1 <- (-b + sqrt(x))/(2*a)
sol_2 <- (-b - sqrt(x))/(2*a)
sprintf("Real Solution 1: %f , Real Solution 2: %f ", sol_1, sol_2)
} else if (x == 0){
sol <- (-b)/(2*a)
sprintf("One Solution: %f ", sol)
} else {
a <- as.complex(a)
x <- (b^2 - 4*a*c)
sol_1 <- (-b + sqrt(x))/(2*a)
sol_2 <- (-b - sqrt(x))/(2*a)
sol_1_c <- as.character(sol_1)
sol_2_c <- as.character(sol_2)
sprintf("Complex Solution 1: %s , Complex Solution 2: %s", sol_1_c, sol_2_c)
}
}
quadratic(1,4,5)
## [1] "Complex Solution 1: -2+1i , Complex Solution 2: -2-1i"
quadratic(1,4,-10)
## [1] "Real Solution 1: 1.741657 , Real Solution 2: -5.741657 "