RPubs URL

  1. Write a loop that calculates 12-factorial.
#The factorial function takes in integer values (negative or positive)
factorial <- function(x) {
  if ( x < 0 ) return (-1 * factorial(abs(x)))
  if (x == 0 | x == 1) return (1)
  else {
    factorial_value <- 1
    for (i in 1:x){
      factorial_value <- factorial_value * i
    }
    return (factorial_value)
  }
}

The call of the function factorial(12) is 4.79001610^{8}

  1. Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.
seq(20, 50, by=5)
## [1] 20 25 30 35 40 45 50
  1. 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. This is based on the Quadratic Formula: \[x = \frac{-b ± \sqrt{b^2 - 4ac}}{2a}\]
#Quadratic Function takes in a, b, and c as arguments
quadratic <- function(a, b, c){
  determine <- determinant(a, b, c)
  if (determine == 0) {
    return (-b / (2*a))
  } else if (determine > 0){
    root1 <- ((-b) + sqrt(determine)/(2*a))
    root2 <- ((-b) - sqrt(determine)/(2*a))
    return (c(root1, root2))
  } else {
    root1 <- ((-b) + sqrt(as.complex(determine))/(2*a))
    root2 <- ((-b) - sqrt(as.complex(determine))/(2*a))
    return (c(root1, root2))
  }
}

#Calculates the determinant from a, b, and c
determinant <- function(a, b, c){
  return ((b^2) - (4*a*c))
}
Examples
  1. \[2x^2 + 4x + 2 = 0\]
  2. \[2x^2 + 8x + 9 = 0\]
  3. \[x^2 - 16 = 0\]
equation_1 <- quadratic(2,4,2)
equation_1
## [1] -1
equation_2 <- quadratic(2,8,9)
equation_2
## [1] -8+0.707107i -8-0.707107i
equation_3 <- quadratic(1,0,-16)
equation_3
## [1]  4 -4