Write a loop that calculates 12-factorial
get_factorial <- function(n = 0) {
# Ideally the code to confirm that n is an integer would go here.
# Since it is not directly requested by the problem, assuming n is integer.
# Check that n is non-negative
if (n < 0) return(-1)
# Return 1 if n is zero
if (n == 0) return(1)
# Loop to calculate factorial
my_factorial <- 1
for (i in 1:n) {
my_factorial <- my_factorial * i
}
return(my_factorial)
}
get_factorial(12)
## [1] 479001600
Show how to create a numeric vector that contains the sequence from 20 to 50 by 5
five_vector <- c(seq.int(20, 50, by = 5))
five_vector
## [1] 20 25 30 35 40 45 50
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.
# Constructing Quadratic Formula
factorial_ <- function(a,b,c){
if(discriminant(a,b,c) > 0){ # first case Discriminant>0
x_1 = (-b+sqrt(discriminant(a,b,c)))/(2*a)
x_2 = (-b-sqrt(discriminant(a,b,c)))/(2*a)
result = c(x_1,x_2)
}
else if(discriminant(a,b,c) == 0){ # second case Discriminant=0
x = -b/(2*a)
}
else {"There are no real roots."} # third case Discriminant<0
}
# Constructing discrimant to determine roots
discriminant<-function(a,b,c){
b^2-4*a*c
}
Example 1
c<-factorial_(1,-4,2)
c
## [1] 3.4142136 0.5857864
Example 2
c<-factorial_(1,-2,-3)
c
## [1] 3 -1