This loop, on its final iteration, finds the product of all integers from 0 less than 12 to 11 less than 12.
x <- 12
factorial <- 1
for (n in 0:11) {
print(factorial)
factorial <- factorial*(x-n)
}
## [1] 1
## [1] 12
## [1] 132
## [1] 1320
## [1] 11880
## [1] 95040
## [1] 665280
## [1] 3991680
## [1] 19958400
## [1] 79833600
## [1] 239500800
## [1] 479001600
This code scales the vector of integers from 4 to 10, inclusive, by 5 to create the desired vector.
twenty_to_fifty_by_five <- 5*c(4:10)
twenty_to_fifty_by_five
## [1] 20 25 30 35 40 45 50
This function uses conditional logic to evaluate the quadratic formula depending on if the discriminant is positive, zero (in which case it evaluates a simplified version of the quadratic formula,) or negative (in which case the solutions are output as complex numbers.)
quad <- function (a,b,c)
if (b**2-4*a*c>0) {
r1 <- (-b+sqrt(b**2-4*a*c))/(2*a)
r2 <- (-b-sqrt(b**2-4*a*c))/(2*a)
two_real_solutions <- list(r1,r2)
return(two_real_solutions)
} else if (b**2-4*a*c==0) {
-b/(2*a)
} else {
c1 <- (-b+sqrt(as.complex(b**2-4*a*c)))/(2*a)
c2 <- (-b-sqrt(as.complex(b**2-4*a*c)))/(2*a)
two_complex_solutions <- list(c1,c2)
return(two_complex_solutions)
}
quad(1,2,1)
## [1] -1
quad(1,6,5)
## [[1]]
## [1] -1
##
## [[2]]
## [1] -5
quad(1,1,1)
## [[1]]
## [1] -0.5+0.8660254i
##
## [[2]]
## [1] -0.5-0.8660254i