Loop to calculate factorial

  1. Write a loop that calculates 12-factorial
get.factorial <- function(n){
  factorial <- 1
  if(n==0 || n == 1){
    factorial <- 1
  } else {
    for(i in 1:n){
      factorial <- factorial*i
    }
    
  }
  sprintf("The factorial of %d is %d", n, factorial)
}
get.factorial(12)
## [1] "The factorial of 12 is 479001600"

Seq function to create sequence of integers

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

s <- seq(from = 20, to = 50, by = 5)
print(s)
## [1] 20 25 30 35 40 45 50
print(class(s))
## [1] "numeric"

Quadractic funcion quard

  1. 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 output the two solutions. Please run and test your answer # # for (1,2,1), (1,6,5) and (1,1,1).
quad <- function(a, b, c){
  # find the numerator, D = (b*b - 4*a*c)^0.5
  D <- (b*b - 4*a*c)^0.5
  
  # find the roots, x1 and x2
  x1 <- (-b + D)/(2*a)
  x2 <- (-b - D)/(2*a)
  
  # print the values of the quadratic
  sprintf("The roots of the quadratic %sx^2 + %sx + %s are: x1: %s, x2: %s", a, b, c, x1, x2)
}
quad(1, 6, 5)
## [1] "The roots of the quadratic 1x^2 + 6x + 5 are: x1: -1, x2: -5"
quad(1, 1, 1)
## [1] "The roots of the quadratic 1x^2 + 1x + 1 are: x1: NaN, x2: NaN"
quad(1, 2, 1)
## [1] "The roots of the quadratic 1x^2 + 2x + 1 are: x1: -1, x2: -1"