JavaScript fun: Decomposition prime factor

Source: Internet
Author: User
The process of dividing a positive integer into several prime factor is called factorization prime factor. For example, the process of dividing a positive integer into several prime factor is called a factorization prime factor.

A simple example:

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

On the computer side, we can use a hash table to store this result. In JS, we can use the following format:

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

So how can we break down the prime factor?

First, 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, short division is used for decomposition.

Function PrimeFactorizer (n) {// hash var hash ={}; while (n> 1) {// remove for (var I = 2 from the minimum prime number; I <= n; I ++) {if (isPrime (I) & n % I = 0) {// if the hash contains this prime number, the number of disks is + 1 if (hash [I]) {hash [I] = hash [I] + 1;} // otherwise, the prime number is used as the key, the value is 1 else {hash [I] = 1;} // remove this minimum prime factor n/= I ;}}// Add the factor attribute this to the instance. factor = hash; hash = null;} new PrimeFactorizer (24 ). factor // {'2': 3, '3': 1}

The above is JavaScript fun: decomposition of the quality factor content, more relevant content please follow the PHP Chinese Network (www.php1.cn )!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.