1. Write a loop that calculates 12-factorial
count <- 12
result <- 1
while (count != 1){
result <- result*count
count <- count - 1
print(result)
}
## [1] 12
## [1] 132
## [1] 1320
## [1] 11880
## [1] 95040
## [1] 665280
## [1] 3991680
## [1] 19958400
## [1] 79833600
## [1] 239500800
## [1] 479001600
2. Show how to create a numeric vector that contains a sequence from 20 to 50 by 5
numeric_vec <- seq(20, 50, 5)
print(numeric_vec)
## [1] 20 25 30 35 40 45 50
# or seq(from=20, to=50, by=5)
3. Create the 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.
#Definition of Quadratic func: f(x) = ax^2 + bx + c where a, b and c are real numbers and a is not equal to zero.
quad_func <-function(a, b, c){
if( a == 0){
print("This equation is linear, not quadratic.")
}else if(a != 0){
#determines the type of root
discriminant = (b^2) - 4 * a * c
if(discriminant > 0){
x1 = (-b + (sqrt(discriminant))) / 2*a
x2 = (-b - (sqrt(discriminant))) / 2*a
print("Roots are real numbers and there are two solutions.")
print(paste("x1 = ", x1, "and x2 = ", x2))
}else if(discriminant == 0){
# a zero value of discriminant does not effect sign of x
print("Equal roots. Thus there is only one solution.")
x1 = x2 = (-b + (sqrt(discriminant))) / 2*a
print(paste("x1 = ", x1))
}else if(discriminant < 0){
print("Roots are complex/imaginary")
}
}
}
#calling exampleq uadratic function to solve equations
quad_func (2 ,5, -30)
## [1] "Roots are real numbers and there are two solutions."
## [1] "x1 = 11.2788205960997 and x2 = -21.2788205960997"
#quad_func (0, 3, 4)
#quad_func (1, -2, 1)
#quad_func (6, 11, 35)