Q1: Write a loop that calculates 12-factorial

A1:

The factorial of a number is the product of all the integers from 1 to that number. So 12-factorial means the product of all numbers from 12* 11* 10 * … * 2*1

result <- 1
for (i in 1:12) {
    result <- result * i
  }
  cat("The factorial of 12 is", result)
## The factorial of 12 is 479001600

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

A2:

There is a built in function called seq() that takes three arguments which are from(start point), to(end point), by(step)

seq_vec <- c(seq.int(from = 20, to = 50, by = 5))
seq_vec
## [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.

A3:

Quadratic equation = \(a*x^{2} + b*x + c = {0}\)

solution => \(x = -b \pm \sqrt{b^{2} - 4ac}\)

quad <- function(a, b, c) {
  # first case: check if the equation is quadratic in the first place
  if (a == 0) {
    return("not a valid equation")
  }
  # set a variable to store the quadratic equation solution
  quad_eq <- (b^2 - 4*a*c)
  # second case: if the solution is equal to zero then there is only one solution
  if (quad_eq == 0) {
    sol <- -b/(2*a)
    return (sprintf("there is only one solution: %s", sol))
    # third case: if the solution is greater than zero then we have two possible solutions
  } else if (quad_eq > 0) {
    sol_1 <- (-b + sqrt(quad_eq))/(2*a)
    sol_2 <- (-b - sqrt(quad_eq))/(2*a)
    return (sprintf("There are two solutions: %s and %s", sol_1, sol_2))
    # forth case: to have two complex solutions (sol is less than zero)
  } else {
    sol1 <- complex(real = -b / (2*a), imaginary = sqrt(-quad_eq)/(2*a))
    sol2 <- complex(real = -b / (2*a), imaginary = - sqrt(-quad_eq)/(2*a))
    return (sprintf("There are two complex solutions: %s and %s", sol1, sol2))
  }
}

quad(0, 1, 0) # 1st case
## [1] "not a valid equation"
quad(1, 2, 1) # 2nd case
## [1] "there is only one solution: -1"
quad(1, -1, -2) # 3rd case
## [1] "There are two solutions: 2 and -1"
quad(1, 1, 1) # 4th case
## [1] "There are two complex solutions: -0.5+0.866025403784439i and -0.5-0.866025403784439i"