Title: “R Bridge Workshop HW1” Author: “Gabriel Castellanos” Date: “2022-12-23” html_document: ---
The goal of the first question is to write a loop that it is the equivalent of
12!. Factorials, along with Fibonacci numbers, are quintesential examples of
recursion. Using a while loop is much less elegent way of accomplishing
this task
findfactorial <- function(n){
factorial <- 1
if(n==0 | n==1){
factorial <- 1
} else{
while(n >= 1){
factorial <- factorial * n
n <- n-1
}
}
return (factorial)
}
findfactorial(12)
## [1] 479001600
The next question asks to create a numeric vector that contains the sequence from 20 to 50 by 5.
MyVector <- seq(20, 50, by=5)
MyVector
## [1] 20 25 30 35 40 45 50
The last question ask to create a function “quadratic” 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) {
print(paste0("You have chosen the following quadratic equation ", a, "x^2 + ", b, "x + ", c, "."))
discriminant <- (b^2) - (4*a*c)
if(discriminant < 0) {
return(paste0("This quadratic equation has imaginary roots."))
}
else if(discriminant > 0) {
x_int_plus <- (-b + sqrt(discriminant)) / (2*a)
x_int_neg <- (-b - sqrt(discriminant)) / (2*a)
return(paste0("This quadratic has two roots ",
format(round(x_int_plus, 5), nsmall = 5), " and ",
format(round(x_int_neg, 5), nsmall = 5), "."))
}
else #discriminant = 0 case
x_int <- (-b) / (2*a)
return(paste0("The quadratic equation has only one root. This root is ",
x_int))
}
quadratic(1,2,3)
## [1] "You have chosen the following quadratic equation 1x^2 + 2x + 3."
## [1] "This quadratic equation has imaginary roots."