1. Write a loop that calculates 12 factorial.

This loop, on its final iteration, finds the product of all integers from 0 less than 12 to 11 less than 12.

x <- 12
factorial <- 1
for (n in 0:11) {
  print(factorial)
  factorial <- factorial*(x-n)
}
## [1] 1
## [1] 12
## [1] 132
## [1] 1320
## [1] 11880
## [1] 95040
## [1] 665280
## [1] 3991680
## [1] 19958400
## [1] 79833600
## [1] 239500800
## [1] 479001600

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

This code scales the vector of integers from 4 to 10, inclusive, by 5 to create the desired vector.

twenty_to_fifty_by_five <- 5*c(4:10)
twenty_to_fifty_by_five
## [1] 20 25 30 35 40 45 50

3. Create the function “quad” that takes a trio of input numbers a, b, and c and solve the quadratic equation. The function should print as an output the two solutions. Please run and test your answer for (1,2,1), (1,6,5) and (1,1,1).

This function uses conditional logic to evaluate the quadratic formula depending on if the discriminant is positive, zero (in which case it evaluates a simplified version of the quadratic formula,) or negative (in which case the solutions are output as complex numbers.)

quad <- function (a,b,c)
  if (b**2-4*a*c>0) {
    r1 <- (-b+sqrt(b**2-4*a*c))/(2*a)
    r2 <- (-b-sqrt(b**2-4*a*c))/(2*a)
    two_real_solutions <- list(r1,r2)
    return(two_real_solutions)
  } else if (b**2-4*a*c==0) {
    -b/(2*a)
  } else {
    c1 <- (-b+sqrt(as.complex(b**2-4*a*c)))/(2*a)
    c2 <- (-b-sqrt(as.complex(b**2-4*a*c)))/(2*a)
    two_complex_solutions <- list(c1,c2)
    return(two_complex_solutions)
  }
quad(1,2,1)
## [1] -1
quad(1,6,5)
## [[1]]
## [1] -1
## 
## [[2]]
## [1] -5
quad(1,1,1)
## [[1]]
## [1] -0.5+0.8660254i
## 
## [[2]]
## [1] -0.5-0.8660254i