javascript - Why does my factorial function always return one? -
i trying write piece of code solve coderbyte challenge, calculate number's factorial. every time run it, factorial generated one. doing wrong?
var num var array1 = new array(); function firstfactorial(num) { (var = num; i>0; i--){ // 8 , 7, 6 , 5 (var y = 0; y<num ; y++){ // 0, 1, 2, 3, 4 array1[y]=i; // have array looks [8,7,6,5,4,3,2,1] }; }; var sum = 1 (var x = 0; x<array1.length; x++){ // want run array, reading #s sum = sum * array1[x]; return sum; }; return sum };
a few issues.
1/ minor but, when multiply 2 numbers, product, not sum.
2/ returned value within loop mean, if fixed other problems, return prematurely without having multiplied numbers.
3/ nested loop not fill array way describe, should check after population. think loops expressed pseudo-code:
for = num downto 1 inclusive: y = 0 num-1 inclusive: array1[y] =
you can see inner loop populating entire array value of current i
. last iteration of outer loop, i
one, sets entire array ones.
4/ in case, don't need array store numbers 1 n
, use numbers 1 n
directly. (again, pseudo-code):
def fact(n): prod = 1 = 2 n inclusive: prod = prod * return prod
Comments
Post a Comment