# Question 1
# Write a loop that calculates 12-factorial

david_factorial <- function (n)
{
  
  if(n == 0)
  {
    fact_total <- 1
  }
  else
  {
    fact_total <- n
    while(n > 1)
    {
      fact_total <- fact_total * (n - 1)
      n <- (n - 1)
      
    }
  }
  
  return (fact_total)
}
# Test Cases

david_factorial(0)
## [1] 1
david_factorial(1)
## [1] 1
david_factorial(2)
## [1] 2
# Calculate 12!

david_factorial(12)
## [1] 479001600
# Check the built-in factorial library

factorial(12)
## [1] 479001600
# Question 2
# Show how to create a numeric vector that contains the sequence from 20 to 50 by 5.

my_vector <- seq(20, 50, by=5)

# print out a vector sequence from 20 to 50 in 5 increments
my_vector
## [1] 20 25 30 35 40 45 50
# Question 3. create a function factorial (named quadratic_function here to not conflict with the built-in factorial function)

quadratic_function <- function(a,b,c)
{
  if (a == 0)
  {
    stop("The values must satisify the formula ax^2 + bx + c")
  }
  else if ((b^2 - (4 * a * c)) == 0)
  {
    print("ax^2 +bx + c has two equal values because the discriminant is equal to zero.")
    x1 = (-b + sqrt(b^2 - (4 * a* c)))/(2 * a)
    x2 = (-b - sqrt(b^2 - (4 * a* c)))/(2 * a)
  }
  else if((b^2 - (4 * a * c)) > 0)
  {
    print("ax^2 +bx + c has two real values because the discriminant is greater than zero.")
    x1 = (-b + sqrt(b^2 - (4 * a* c)))/(2 * a)
    x2 = (-b - sqrt(b^2 - (4 * a* c)))/(2 * a)
  }
  else if((b^2 - (4 * a * c)) < 0)
  {
    print("ax^2 +bx + c has two complex values because the discriminant is less than zero.")
    x1 = (-b + sqrt(as.complex(b^2 - (4 * a* c))))/(2 * a)
    x2 = (-b - sqrt(as.complex(b^2 - (4 * a* c))))/(2 * a)
  }
  sprintf("x1 = %s, x2 = %s", x1, x2)
}

# test cases

# ax^2 +bx + c has two values
quadratic_function(1,-2,-4)
## [1] "ax^2 +bx + c has two real values because the discriminant is greater than zero."
## [1] "x1 = 3.23606797749979, x2 = -1.23606797749979"
# x1 and x2 are equal

quadratic_function(9,12,4)
## [1] "ax^2 +bx + c has two equal values because the discriminant is equal to zero."
## [1] "x1 = -0.666666666666667, x2 = -0.666666666666667"
# Imaginary numbers
quadratic_function(2,-6,5)
## [1] "ax^2 +bx + c has two complex values because the discriminant is less than zero."
## [1] "x1 = 1.5+0.5i, x2 = 1.5-0.5i"