Search code examples
rloopsfor-loopfactorial

Factorial for loop


I created the following funcion to calculate the factorial of a given number:

factorial <- function(x){
y <- 1
for(i in 1:x){
y <-y*((1:x)[i])
print(y)
}

}


factorial(6)

in console:

[1] 1
[1] 2
[1] 6
[1] 24
[1] 120
[1] 720

6!=720 so obviously the last number is correct and the calculation does work for all numbers.

The problem is I only want the last number to be printed to console, is there any way to do that? I´ve been trying to turn y into a vector within the function but it doesn`t seem to work.


Solution

  • Move the print statement outside the loop?

    for(i in 1:x){
        y <-y*((1:x)[i])
    }
    print(y)