First, I created a function and assigned “y” for a number “n.” Assigned initial value “x” for loop as 1. Factorials can only be non-zero positive integers, with the lowest value as 1. I then wrote a loop for the range 1:n, where “n” is user-defined later. As the loop iterates, it multiplies x by i, which is each number in the defined range, starting with 1 * 1, until reaching the n’th number.
y <- function (n) {
x <- 1
for (i in 1:n) {
x <- x * i
}
return(x)
}
y(12)
## [1] 479001600
From additional quiz question 11, using the sequence function, “sec.” Syntax: starting value, ending value, interval.
seq(20,50,5)
## [1] 20 25 30 35 40 45 50
Using the quadratic formula:
\(x=\frac{-b\pm\sqrt{b^2 - 4ac}}{2a}\)
First, created a function named “quadratic.” I provided the function with three arguments for input, “a”,“b”, and “c.” Taking careful note of the order of operations, I wrote out the formula. The most difficult aspect of this problem was how to produce both solutions. After a bit of searching, I found an example of creating two separate lines for the “plus” solution and the “minus” solution. After a bit more digging, I found a really elegant solution to use “combine,” since the code will iterate automatically for all values in the vector.
quadratic <- function(a,b,c){
x = (-b + (c(-1,1)*sqrt(b^2-4*a*c)))/(2*a)
return(x)
}
quadratic(2,4,-30)
## [1] -5 3