Question 1

Write a loop that calculates 12-factorial

# intializing 
twel_factorial <- 1
for (i in 1:12) {
  twel_factorial <- twel_factorial * i
}
print(twel_factorial)
## [1] 479001600

Question 2

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

# The simplest way is with R seq(from = , to = , by = ,...) function
numvec <- seq(20, 50, by = 5)

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

Question 3

Create the fuction “factorial”1 that takes a trio of input numbers a, b, and c and solve the quadric equation. The function should print as output the two solutions.
1 I believe this was a typo since factorial(x) is already a function in R, therefore, the function is called solve_quadratic instead.

solve_quadratic <- function(a, b, c){
  # FUNCTION : solve_quadratic solves a quadratic equation: ax^2 + bx + c = 0.
  # INPUT : a , b, c; class = numeric
  # OUTPUT : two solutions, if any by solving x = (-b ± sqrt(b^2 - 4ac))/ 2a.
  
  # Check to see if the equation is quadratic.
  if (a == 0){
    return("Equation is not quadratic.")
  }
  
  # Find the discriminant (b^2 - 4ac), because with a positive discriminant, the roots are real, a 0 discriminant indicates a single real root and a negative discriminant indicates imaginary roots.
  
  discriminant <- (b^2) - (4*a*c)
  
  # Now find the roots
  
  # For two real roots
  if (discriminant > 0) {
    x1 <- (-b + sqrt(discriminant))/ (2*a)
    x2 <- (-b - sqrt(discriminant))/ (2*a)
    return(sprintf("%s and %s are the real solutions of the quadratic equation.", x1, x2))
  }
  # For one real root
  else if (discriminant == 0) {
    x1 = -b / (2*a)
    return(sprintf("%s is the only solution for the quadratic equation.", x1))
  }
  # For imaginary roots
  else {
    x1 <- complex(real = -b / (2*a), imaginary = sqrt(-discriminant) / (2*a))
    x2 <- complex(real = -b / (2*a), imaginary = -sqrt(-discriminant) / (2*a))
    return(sprintf("%s and %s are the complex solutions of the quadratic equation.", x1, x2))
  }
}

Example 1 with two real solutions

solve_quadratic(8, -11, -5)
## [1] "1.73519091339001 and -0.360190913390013 are the real solutions of the quadratic equation."

Example 2 with one solution

solve_quadratic(1, -8, 16)
## [1] "4 is the only solution for the quadratic equation."

Example 3 with complex solutions

solve_quadratic(6, 5, 10)
## [1] "-0.41666666666667+1.2219065248846i and -0.41666666666667-1.2219065248846i are the complex solutions of the quadratic equation."

Example 4 that is not quadratic

solve_quadratic(0, 5, 25)
## [1] "Equation is not quadratic."