Summary of JavaScript method for determining whether a number is a prime number, javascript Prime Number

Source: Internet
Author: User

Summary of JavaScript method for determining whether a number is a prime number, javascript Prime Number

Preface

Today, I saw a question that makes it difficult to determine whether a number is a prime number. Therefore, I decided to implement it.

DOM Structure

<! DOCTYPE html> 

As shown above, we use the isPrimeNum (num) function to determine whether it is a prime number. Next we will implement this function.

Use the FOR loop to determine whether it is a prime number

function isPrimeNum(num){for (var i = 2; i < num; i++) {if (num%i==0){return false;}};return true;}

The principle is relatively simple. If the remainder is obtained from a number greater than 2 and the target number is obtained, it indicates that this is a combination of numbers rather than a prime number.

However, this operation volume seems to be large.

Optimize the first method

It's very easy. however, it seems you can optimize it. we don't seem to have to keep chasing this number to calculate the remainder. We just need to loop to half of this number to calculate whether this number is a prime number.

function isPrimeNum(num){for (var i = 2; i < num/2+1; i++) {if (num%i==0){return false;}};return true;}

After the test, the speed is indeed greatly improved. However, I know that the ending number of a number is double or 5, so it is definitely not a prime number, so it is not necessary to calculate it. Let's optimize it.

Do not calculate the number whose ending number is double or 5

function isPrimeNum(num){if (!isDual(num)){return false;}for (var i = 2; i < num/2+1; i++) {if (num%i==0){return false;}};return true;}function isDual(num){var num = num.toString();var lastNum = num.substring(num.length-1,num.length);return lastNum%2 == 0 || lastNum%5 == 0 ? false : true;}

Through such optimization, we can reduce the computational workload by at least half of the number. (However, the actual test improves the performance. Because of this number, we can quickly determine that it is not a prime number)

Here, the substring () function finds that it can only be used on strings instead of numbers. It turns numbers into strings first.

If it is not a number or integer

What if the user does not input a number or a decimal number? I quickly wrote two methods for processing...

function isPrimeNum(num){if (!isNum(num)){return false;}if (!isInteger(num)){return false;}if (!isDual(num)){return false;}for (var i = 2; i < num/2+1; i++) {if (num%i==0){return false;}};return true;}function isInteger(num){return num == ~~num ? true : false;}function isNum(num){return num == +num ? true : false;}function isDual(num){var num = num.toString();var lastNum = num.substring(num.length-1,num.length);return lastNum%2 == 0 || lastNum%5 == 0 ? false : true;}

Two tips are used here. One is to integer the number of digits ~~ Num. One is a string to a number. + num.

For more information, please read my previous blog post "javascript learning summary JS Loading Techniques (I) by FungLeo"

This does not improve performance, but eliminates the need to calculate incorrect input. Let's try again. Is there any way to quickly judge whether it is not a prime number?

Remove the number that can be divisible by 3 and do not calculate it

function isPrimeNum(num){if (!isNum(num)){return false;}if (!isInteger(num)){return false;}if (num==2||num==3||num==5) {return true;}if (!isDual(num)){return false;}if (!isThree(num)){return false;}for (var i = 2; i < num/5+1; i++) {if (num%i==0){return false;}};return true;}function isInteger(num){return num == ~~num ? true : false;}function isNum(num){return num == +num ? true : false;}function isDual(num){var num = num.toString();var lastNum = num.substring(num.length-1,num.length);return lastNum%2 == 0 || lastNum%5 == 0 ? false : true;}function isThree(num){var str = num.toString();var sum = 0;for (var i = 0; i < str.length; i++) {sum += +str.substring(i,i+1);};return sum%3 == 0 ? false : true;}

Here, we first convert the number into a string, then split each character in the string, and add and sum, and obtain the result and 3 for remainder, then we can see whether the number can be fully divided by 3.

Haha, I am so smart... The tested performance does not seem to improve much, but it does improve a little.

However, if we exclude three divisible numbers, we do not need to calculate half of them. We do not need to calculate half of them. We only need to calculate 1/3. in addition, we also ruled out 5, so as long as the calculation reaches 1/5 ....

After rapid adjustment, the efficiency has been greatly improved !!!! My mighty...

However, in this case, the code will determine the number of three prime numbers in 2 \ 3 \ 5. Therefore, you need to add another sentence.

if (num==2||num==3||num==5) {return true;}

Others' Methods

Then I can't think of the optimization method... So I searched and found the solution below. I was shocked !!!!!

function isPrimeNum2(num){return !/^.?$|^(..+?)\1+$/.test(Array(num + 1).join('1'))}

The regular expression method is used. It is really short, but I can understand it !!!

I really don't understand how this works. I tested it and found that my code is much more efficient than this code. It can be seen that my method is still very good !!

It takes 100000 ms for my code to print all the prime numbers of less than 1600, and 160000 ms for this code. That is to say, my code only needs 1% of the time.

However, please help me explain who can understand this code ....

Supplement

I read some related information, as if I used num/5 above, it seems that the result is not wrong ). A better way is to use Math. sqrt (num) returns the square root.

The test results of my Code are as follows:

As shown in, the calculation result of my code is completely correct, but the time is 1638 milliseconds. This is still the case after multiple tests.

The test results are as follows:

As shown in, this method is more scientific, faster, and used for multiple tests, ranging from 1150 ms to 1250 Ms. The performance of my code is improved by about 25%.

I also judge whether the number of digits is double or five, and whether the sum can be divided by three, tossing for half a day. I certainly want to reduce the workload. however, these codes are also computation-intensive. I will remove all my code and then read it again.

Performance has been improved again. It seems that all my calculations are negative optimization!

The Code is as follows:

function isPrimeNum(num){if (!isNum(num)){return false;}if (!isInteger(num)){return false;}for (var i = 2; i <= Math.sqrt(num); i++) {if (num%i==0){return false;}};return true;}function isInteger(num){return num == ~~num ? true : false;}function isNum(num){return num == +num ? true : false;}

Summary: I am not doing well in arithmetic, which leads to all sorts of Self-intelligence in front of me. However, it is also good to practice small skills-_-|

Finally, let's take a look at how long it takes to calculate all the prime numbers of less than 1 million.

The above is a summary of the JavaScript method used to judge whether a number is a prime number. I hope it will help you.

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.