Johnny Depp
Johnny Depp

Reputation: 171

Getting Result as Undefined while finding out Prime Factors

So i am working on a simple code to find all prime factors of a number, i can do it using for loop but i tried this approach ,so if someone can help me with the output as it's coming undefined. I tried using for loop and it's working but when using this method i get undefined.

let arr1=[]; 
let recursion={
    primeFactorize:(num,n=2)=>
    {
        if(num%n==0 && n<=num)
        {
            arr1.push(n);
            num/=n;
            recursion.primeFactorize(num,n+=1);
        }
        else if(n>num){
            return arr1;
        }
        else{
            recursion.primeFactorize(num,n+=1);
        }
    }
};
console.log(recursion.primeFactorize(35));

Expected result is Array but i get an undefined.

Upvotes: 0

Views: 61

Answers (2)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23399

The function doesn't return anything, it just builds the array. Try logging the array instead.

let arr1=[]; 
let recursion={
    primeFactorize:(num,n=2)=>
    {
        if(num%n==0 && n<=num)
        {
            arr1.push(n);
            num/=n;
            recursion.primeFactorize(num,n+=1);
        }
        else if(n>num){
            return arr1;
        }
        else{
            recursion.primeFactorize(num,n+=1);
        }
    }
};

recursion.primeFactorize(35)
console.log(arr1);

Upvotes: 1

You're not returning anything in the recursive cases. Put return before recursion.primeFactorize in both places it appears inside of itself.

Upvotes: 0

Related Questions