My question is related to calculate the multiplies of 12 (factorials) in a for loop:
I spent a lot of time on this but can`t solve it!
It is important to use a function with a 'for' loop!
So far: I had tried doing
for(i in 1:12){
prod(i)
}
and also
for(i in 1:12){
print(prod(i)
}
and also
for(i in 1:12){
prod(i)
}
and also
for(i in 1:12){
print(prod(i)
}
and also
many other code, and it does not work
CodePudding user response:
For:
my_factorial<-function(x){
y<-1
for(i in 1:x) {
y<-y*((1:x)[i])
}
return(y)
}
my_factorial(12)
is the same as:
factorial
factorial(12)
OR
You can use gamma
for factorials:
x = 12
gamma(x 1)
is the same as:
12*11*10*9*8*7*6*5*4*3*2*1
[1] 479001600
result:
[1] 479001600
CodePudding user response:
If you want product of first numbers at each iteration
b=vector()
for (i in 1:12){
b[i]=i
print(prod(b))
}
[1] 1
[1] 2
[1] 6
[1] 24
[1] 120
[1] 720
[1] 5040
[1] 40320
[1] 362880
[1] 3628800
[1] 39916800
[1] 479001600
This will be like
1
1*2
1*2*3
.
.
.
1*2*3*4*5*6*7*8*9*10*11*12
But if you want just the product of the 12 first positive integers then you do not need a for
loop. just use product function.
prod(1:12)
[1] 479001600