MSDS HW1 - Bridge Program R

1. Write a loop that calculates 12-factorial

fact <- 1
      for (x in 1:12) { 
      fact <- fact * x
      cat (x, "!", fact,"\n") 
     
       
      }     
## 1 ! 1 
## 2 ! 2 
## 3 ! 6 
## 4 ! 24 
## 5 ! 120 
## 6 ! 720 
## 7 ! 5040 
## 8 ! 40320 
## 9 ! 362880 
## 10 ! 3628800 
## 11 ! 39916800 
## 12 ! 479001600
  print("The Factorial of 12 is 479001600")
## [1] "The Factorial of 12 is 479001600"

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

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

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.

fact <- function (a, b, c){
  delta <- (b^2) - (4*a*c)
  if (delta > 0){
    xpos = (-b + sqrt(delta))/(2*a)
    xneg = (-b - sqrt(delta))/(2*a)
  
    return(paste("The answers are:", "x+:", xpos, "and", "x-:", xneg))
    
  }else if (delta == 0){
    x = -b/(2*a)
    return(paste("The answer is: ", x))
    
  }else{
    "No real roots"
  }
}

fact(1/4,-2,3)
## [1] "The answers are: x+: 6 and x-: 2"