Question 1

Write a loop that calculates 12-factorial

x = 12
fact <- 1
for( i in 1:x)
{
  fact <- fact*i
}
print(fact)
## [1] 479001600

Question 2

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

## [1] 20 25 30 35 40 45 50

Question 3

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){
  radicand = b**2 - 4*a*c
  if(is.na(a) || is.na(b) || is.na(c)){
    return("NA")
  }
  if (a == 0 && b == 0){
    return("No x-values. No solution.")
  }  else if (a == 0){
    x <- -c/b
    return(paste0("Not Quadratic: x = ",
                  format(round(x, 4), nsmall = 1)))
  } else if (radicand > 0){
    qpos <- (-b + (radicand)**(1/2))/(2*a)
    qneg <- (-b - (radicand)**(1/2))/(2*a)
    return(paste0("The two x-intercepts are: x = ",
                  format(round(qpos, 4), nsmall = 1), " and x =  ",
                  format(round(qneg, 4), nsmall = 1)))
  } else if (radicand == 0){
    qpos <- (-b + (radicand)**(1/2))/(2*a)
    qneg <- (-b - (radicand)**(1/2))/(2*a)
    return(paste0("ONE SOLUTION: x = ",
                  format(round(qpos, 4), nsmall = 1)))
  } else
    realpart <- (-b)/(2*a)
    comppart <- (((-1)*(radicand))**(1/2))/(2*a)
    return(paste0("COMPLEX SOLUTIONS:", cat("\n"),
                  "x = ", format(round(realpart, 4), nsmall=1),
                  " + ", format(round(comppart, 4), nsmall=1),
                  "i and x = ", format(round(realpart, 4), nsmall=1),
                  " - ", format(round(comppart, 4), nsmall=1), "i"))
}

#In RStudio, this is how I request user input for individual cases.
#This does not work when Knitting because knit does not allow readline inputs
#a <- as.numeric(readline(prompt="Enter 2nd degree Coefficient: "))
#b <- as.numeric(readline(prompt="Enter 1st degree Coefficient: "))
#c <- as.numeric(readline(prompt="Enter Constant: "))

#quadratic(a,b,c)
#test cases: 
quadratic(1,-2,1)
## [1] "ONE SOLUTION: x = 1.0"
quadratic(3,5,1)
## [1] "The two x-intercepts are: x = -0.2324 and x =  -1.4343"
quadratic(2.1,4,10)
## [1] "COMPLEX SOLUTIONS:x = -0.9524 + 1.9634i and x = -0.9524 - 1.9634i"