Question 1: Write a loop that calculates 12-factorial

Answer

This is a very inefficient way to write this. Moreover, it would probably be easier to write a general function and use recursion. That being said, specifically falculating 12 factorial using a loop, we pre-populate the answer with \(1\) as it is the multiplicative identity.

fact12 <- 1
for (i in seq_len(12)){
fact12 <- fact12 * i
}
fact12 == factorial(12L)
## [1] TRUE

Question 2: Show how to create a numeric vector that contains the sequence from 20 to 50 by 5

Answer

seq(from = 20L, to = 50L, by = 5L)
## [1] 20 25 30 35 40 45 50

Question 3: 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.

Answer

Note that overwriting an existing R function is poor practice.

factorial <- function(a, b, c){
  determinant <- sqrt(b ^ 2 - 4 * a * c)
  denominator <- 2 * a
  return(list(MorePositiveRoot = (-b + determinant) / denominator,
        LessPositiveRoot = (-b - determinant) / denominator))
}

Test

\(x^2 + 8x + 15\) has the roots \((-3, -5)\) since it factors into \((x+3)(x+5)\)

factorial(1, 8, 15)
## $MorePositiveRoot
## [1] -3
## 
## $LessPositiveRoot
## [1] -5