# Factorialize a Number challenge

Factorialize a Number challenge
0

#1

function factorialize(num) {
var result = 1;
if (num > 0) {
for (var i = 1; i <= num; i++) {
result = result * i;
}
}
num = 1;

return result;
}

factorialize(-7);

I know that there is other more simple solution but I only wanted to focus on my way of thinking .
I am doing these challenges for a week to get used to the “logical thinking” and it is really hard. I hope 1 day I get better at writing because the are a lot of amazing terms, methods, function, prototypes to learn =)

#2

OPS, LET ME CORRECT AND PUT SOME COMMENTS

function factorialize(num) {
var result = 1; // result is assigned with 1
if (num > 0) { // if this condition is true, then result will be assigned with other value.
for (var i = 1; i <= num; i++) {
result = result * i;
}
}

return result;
}

factorialize(-7);

#3
1. The factorial of 1 is 1, you can change your `if` condition so that your for loop is not executed in that case (like you did for for num = 0).
2. Instead of `result = result * i` you can use the equivalent `result *= i`, which means "multiply `result` by `i`".
3. With your function, the factorial of any negative number would be 1, which is wrong. You should return another value (for example `undefined`) if someone tries to find the factorial of a negative number.
4. You can format your code putting it between backtick characters:

my code

``````function factorialize(num) {
var result = 1; // result is assigned with 1
if (num > 0) { // if this condition is true, then result will be assigned with other value.
for (var i = 1; i <= num; i++) {
result = result * i;
}
}

return result;
}

``````

#5

You are right and I did not find anyone writing about negative values. So what should I do?

#6
``````function factorialize(num) {
var result = 1; // result is assigned with 1
if (num > 0) { // if this condition is true, then result will be assigned with other value.
for (var i = 1; i <= num; i++) {
result = result * i;
}
}
if  (num < 0) {
result = undefined;
}

return result;
}

factorialize(-7);

``````

#7

I inserted another if, since else would not be logical to put. Is it alright now?

#8

Generally you should check error cases first, so your program doesn’t do unnecessary work.
Put your second `if` at the beginning. And you don’t have to do `result = undefined` - if you return without value it defaults to `undefined`. So the first line could be:

``````function factorialize(num) {
if  (num < 0) return; // number is invalid, return undefined
...
...
``````

#9

Tks! Did not know that just putting return it could work!

#10

a more primitive solution from a non-professional///
function factorialize(num) {

var k=num;
if (num>0) {
for (var i=num;i>2;i–){
k=k*(num-1); num= num-1;
} }
if (num===0){
k=1;}
return k;
}

factorialize(5);
///