#Don Padmaperuma #Week 1 R Bridge Homework

Calculate factorial of 12 in R

find_factorial <- function (FN){
calculatefactorial <- 1
for (i in 1: FN){
  calculatefactorial <- calculatefactorial*i
}
return (calculatefactorial)
}
find_factorial (12)
## [1] 479001600

numeric vector that contains the sequence from 20 to 50 by 5

my_vector <- (seq.int (20, 50, by = 5))
my_vector
## [1] 20 25 30 35 40 45 50

Create the function “factorial” that takes a trio of input numbers a, b, and c and solve the quadratic equation

Quadratic eqation ax^2+bx+c=0

factorial <- function(a,b,c){
  #check if the equation is quadratic
  if(a==0){
    return ("Equation is not quadratic")
  }
  
  delta <- (b^2 - 4*a*c)
  #If the discriminant(delta) is positive, then there are two distinct roots
  if (delta>0)
  {
    root1<-((-b+sqrt(delta))/(2*a))
    root2<-((-b-sqrt(delta))/(2*a))
    return (sprintf("Equation has two real roots: %s and %s", root1, root2))
  }
  #If the discriminant(delta) is zero, then there is exactly one real root
  else if (delta == 0){
    root<-(-b/(2*a))
    return(sprintf("Equation has one real root: %s", root))
  }
  #If the delta is negative, then there are no real roots. Rather, there are two (non-real) complex roots
  else 
    root1<- complex(real = -b/(2*a), imaginary = sqrt(-delta)/(2*a))
    root2<- complex(real = -b/(2*a), imaginary = -sqrt(-delta)/(2*a))
    return(sprintf("Equation has two complex roots: %s and %s", root1, root2))
}

Solution 1

factorial(0,2,1)
## [1] "Equation is not quadratic"

Solution 2

factorial(1,-1,-2)
## [1] "Equation has two real roots: 2 and -1"

Solution 3

factorial(1,2,1)
## [1] "Equation has one real root: -1"

Solution 4

factorial(1,2,2)
## [1] "Equation has two complex roots: -1+1i and -1-1i"