Home >Web Front-end >JS Tutorial >JavaScript Fun Question: Factoring Prime Factors

JavaScript Fun Question: Factoring Prime Factors

黄舟
黄舟Original
2017-01-22 14:44:132791browse

The process of decomposing a positive integer into several prime factors is called decomposing prime factors.

A simple example:

The decomposed prime factor of 24 is 2*2*2*3, which is abbreviated as (2^3) * (3^1).

In terms of computers, we can use a hash table to store this result, which can be expressed in the following form in JS:

{ '2': 3, '3': 1 }

So, how to decompose prime factors?

First of all, you need a method to determine whether it is a prime number.

function isPrime(n){  
    for(var i=2;i<=Math.sqrt(n);i++){  
        if(n % i == 0){  
            return false;  
        }  
    }  
    return true;  
}

Then, use short division to decompose.

function PrimeFactorizer(n){  
    //用来存储结果的hash  
    var hash = {};  
    while(n > 1){  
        //从最小的质数开始除  
        for(var i=2;i<=n;i++){  
            if(isPrime(i) && n % i == 0){  
                //如果hash中有这个质数,则存储的数目+1  
                if(hash[i]){  
                    hash[i] = hash[i] + 1;  
                }//否则把该质数作为key,value为1  
                else{  
                    hash[i] = 1;  
                }  
                //除掉这个最小的质数因子  
                n /= i;  
            }  
        }  
    }  
    //给实例上加个factor属性  
    this.factor = hash;  
    hash = null;  
}  
  
new PrimeFactorizer(24).factor // { &#39;2&#39;: 3, &#39;3&#39;: 1 }

The above is an interesting JavaScript question: decomposing prime factors. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn