Problem 1 asks us to write a loop that calculates 12-factorial. Here is how we may write such a function:
fac <- function(x)
{
ans <- 1 # Initialize our answer variable
i <- 2 # Initialize our iterator. We start at 2 because 1! = 1
while(i <= x) # Loop until we get to x
{
ans <- ans * i
i <- i + 1
}
return(ans)
}
We can test the function easily and see that it returns the proper value for 12!:
fac(12)
## [1] 479001600
For problem 2, we are asked to create a numeric vector that contains the sequence from 20 to 50 by 5. The R code to do this is:
vec <- seq(20,50, by=5)
vec
## [1] 20 25 30 35 40 45 50
Finally, for problem 3, we are asked to create a function that takes a trio of input numbers a, b, and c to solve a quadratic equation. The function should print as output the two solutions. If you recall your pre-calculus, a quadratic equation is a function formatted like this: \(ax^2+bx+c=0\) The Qudratic Formula accomplishes this task nicely: \[\begin{array}{*{20}c} {x = \frac{{ - b \pm \sqrt {b^2 - 4ac} }}{{2a}}}\end{array}\] However, there are two caveats we need to watch out for though:
So our function must test for these cases.
factorial<-function(a,b,c)
{
# First let's check if a=0
if(a==0)
{
return(NA)
}
# Compute the discriminant
disc <- (b^2)-4*a*c
# Check for negative discriminant
if(disc < 0)
{
return(NA)
}
# Compute the positive root
pos <- ((-1*b) + (disc)^.5) / (2*a)
# Compute the negative root
neg <- ((-1*b) - (disc)^.5) / (2*a)
# Return our answer
return(c(pos,neg))
}
Now let’s check some examples: \[x^2+3x-4=0\]
factorial(1,3,-4)
## [1] 1 -4
\[0x^2+3x-4=0\]
factorial(0,3,-4) # Here a=0, so we should get NA as a result
## [1] NA
\[x^2+4x+5=0\]
factorial(1,4,5) # Here the discriminant will be negative, so the roots will be imaginary.
## [1] NA
As you see above, we get NA as expected.