#1. Write a loop that calculates 12-factorial
FactorialLoop <- function(Num)
{
Result <- 1 # initialize Result variable as 1
for (i in 1:Num) # Loop through 1 to input Num
{
Result <- Result * i # Multiply numbers in loop and store in Result
}
print(Result) # Print final Result
}
FactorialLoop(12) # Get 12!
## [1] 479001600
#2. Show how to create a numeric vector that contains the sequence from 20 to 50 by 5
SeqVector <- seq(20,50,5) # Create vector from 20 to 50 stepping by 5
SeqVector
## [1] 20 25 30 35 40 45 50
#3. Create the function “factorial” that takes a trio of input numbers a, b, and c and solve the quadratic equation.
FactorialFunc <- function(a, b, c)
{
delta <- b^2 - (4*a*c) # Create delta variable used in square root
if (delta >= 0) # Look to see if results will be real
{
x1 <- (-b + sqrt(delta))/(2*a)
x2 <- (-b - sqrt(delta))/(2*a)
}
else # Look to see if results will be imaginary
{
x1 <- as.complex((-b + sqrt(-delta))/(2*a)) #Multiply delta by -1 and make complex
x2 <- as.complex((-b - sqrt(-delta))/(2*a))
}
print(paste("x1 =", x1))
print(paste("x2 =", x2))
}
FactorialFunc(1,4,4)
## [1] "x1 = -2"
## [1] "x2 = -2"