R Bridge Assignment 1

By Md Forhad Akbar
July 19, 2019

1. Write a loop that calculates 12-factorial

factorial_num <- function(n) {
  if(n <= 1) {
    return(1)
  } else { 
    return(n * factorial_num(n-1))
  }
}

factorial_num(12)
## [1] 479001600

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

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

3. 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.

quadratic <- function(a, b, c) {
  # Check that the equation is quadratic.
  if (a == 0) {
    return("Equation is not quadratic")
  }
  
  delta <- (b^2 - 4 * a * c)
  if (delta > 0) {
    # Two real solutions
    solution1 <- (-b + sqrt(delta)) / (2 * a)
    solution2 <- (-b - sqrt(delta)) / (2 * a)
    return(sprintf("Equation has two real solutions: %s and %s", solution1, solution2))
  } else if (delta == 0) {
    # One real solution
    solution1 <- -b / (2 * a)
    return(sprintf("Equation has only one solution: %s", solution1))
  } else {
    # Two complex solutions
    solution1 <- complex(real = -b / (2 * a), imaginary = sqrt(-delta) / (2 * a))
    solution2 <- complex(real = -b / (2 * a), imaginary = - sqrt(-delta) / (2 * a))
    return(sprintf("Equation has two complex solutions: %s and %s", solution1, solution2))
  }
}

Example 1

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

Example 2

quadratic(1, 2, 1)
## [1] "Equation has only one solution: -1"

Example 3

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

Example 4

quadratic(5, 7,-11)
## [1] "Equation has two real solutions: 0.940121946685673 and -2.34012194668567"

Example 5

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