R Bridge Homework 1

  1. Write a loop that calculates a 12-factorial:
factorial <- function(x) {
  # takes an integer and returns its factorial
  total <- x
  while (x > 1) {
    total <- total * (x - 1)
    x <- x - 1
  }
  return(total)
}

factorial(12)
## [1] 479001600
  1. Create a numeric vector that contains the sequence from 20 to 50 by 5:
v <- seq(20, 50, by=5)
v
## [1] 20 25 30 35 40 45 50
class(v)
## [1] "numeric"
  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.
quadratic <- function(a, b, c){
  if ((is.numeric(a) && is.numeric(b) && is.numeric(c) == TRUE) && (a != 0)) {
  d <- b^2 - (4*a*c) # calculate discriminant
  }
  
  else {
    print("Invalid entry")
  }
    
  if (d > 0) {
    x1 <- (-b + sqrt(b^2 - (4*a*c)))/(2*a)
    x2 <- (-b - sqrt(b^2 - (4*a*c)))/(2*a)
    return(c(x1, x2))
    }
  else if (d == 0) {
    x <- -b/(2*a)
    return(x)
  }
  else {
    print("There is no real solution")
  }
}

quadratic(1, 4, 3)
## [1] -1 -3