Week 1 Homework-CUNY MSDS

Q1. Write a loop that calculates 12-factorial

getwd()
## [1] "C:/Users/Emahayz_Pro/Desktop"
setwd("C:/Users/Emahayz_Pro/Desktop")

Calc_factorial <- function (n){
  if (n < 0) return (-1) # This will check that n is not negative
  if (n == 0) return (1) # This will reurn 1 if n is zero
  m <- 1
  # Calculating the factorial using Loop
  for(i in 1:n){
    m <-m*((1:n)[i])
    print(m)
  }
  
}
# For any given value such as 12 and the factorial is calculated.
Calc_factorial(12)
## [1] 1
## [1] 2
## [1] 6
## [1] 24
## [1] 120
## [1] 720
## [1] 5040
## [1] 40320
## [1] 362880
## [1] 3628800
## [1] 39916800
## [1] 479001600

Q2. Show how to create a numeric vector that contains the sequence from 20 to 50 by5.

Sequence_numb <- vector() #This is an  empty numeric vector
for(i in 20:50){
  
  if(i %% 5 == 0)
  {
    Sequence_numb <-append(Sequence_numb, i)
    
    }
  
}
Sequence_numb #Shows sequence of numeric vector from 20 to 50
## [1] 20 25 30 35 40 45 50

Q3. 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.

Quad_factorial <- function (a, b, c){ 
  theta <- (b^2) - (4*a*c)
  if(theta > 0)
  {x1_positive <- (-b + sqrt(theta)) / (2*a)
  x1_negative <- (-b - sqrt(theta)) / (2*a)
  return(paste("The solution are", x1_positive, "and", x1_negative, "."))}
  else if(theta < 0)
  {return(paste("No possible solution exist for the equation"))}
  else x2_oneanswer <- (-b) / (2*a)
  return(paste("The solution is", x2_oneanswer))}

# Check with Examples

Quad_factorial (1,1,-2)
## [1] "The solution are 1 and -2 ."
Quad_factorial (4,3,-7)
## [1] "The solution are 1 and -1.75 ."
Quad_factorial (2,-1,-5)
## [1] "The solution are 1.85078105935821 and -1.35078105935821 ."
Quad_factorial (4,5,2)
## [1] "No possible solution exist for the equation"