JavaScript to determine whether the number is a prime method summary _javascript Tips

Source: Internet
Author: User
Tags square root

Objective

Today I see a topic that determines whether a number is prime. It doesn't look that hard. So I decided to do it.

DOM structure

<! DOCTYPE html>
 
 

As shown above, we use the Isprimenum (NUM) function to determine whether it is a prime number. Let's implement this function here.

To determine whether a prime number is based on a for loop

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

The principle is relatively simple, through more than 2 of the number of constant and target numbers to find the remainder, if you can get 0, it means that this is a composite rather than prime.

But it seems to be a bit large.

Optimize the first method

It's very simple. But, it seems to be able to optimize. It seems that we don't have to keep chasing the numbers to find the remainder, and we just need to loop around half of that number to figure out if that number is prime.

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

After the actual measurement, the speed is really greatly improved, but I know that the number of the mantissa is even, or 5, then certainly not prime, so there is no need to calculate. Let's optimize it.

Numbers that do not calculate the mantissa of numbers 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.tostring ();
var lastnum = num.substring (num.length-1,num.length);
return lastnum%2 = = 0 | | lastnum%5 = 0? false:true;
}

Through this optimization, we can reduce the computational volume, at least reduce the number of half oh. (But the measured lifting performance is general, because such a number can be quickly judged not prime)

Here the substring () function finds that it cannot be used on numbers, only on strings. Sad reminders, so first the number into a string.

If it is not a number or integer processing

What if the user doesn't enter a number, or a decimal? I quickly wrote two ways to deal with ...

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.tostring ();
var lastnum = num.substring (num.length-1,num.length);
return lastnum%2 = = 0 | | lastnum%5 = 0? false:true;
}

Here are two tips, one is decimal rounding ~~num, and the other is a string number. +num.

Learn more please read my previous blog "JavaScript learning summary JS loading skills (a) by Fungleo"

This does not improve the performance, just eliminates the calculation error input. Let's think again, is there any quick way to judge a prime?

Removing numbers that are divisible by 3 does not count

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.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 turn the number into a string, and then split the string each bit out, and add sum, take the result and 3 to find out, we can get this number can be 3 whole.

Haha, I'm so smart ... The measured performance does not seem to improve a lot, but it does improve some. A little depressed.

However, if we exclude 3 divisible numbers, then we have absolutely no need to calculate half of it, we do not need to calculate the half, only to calculate to One-third. In addition, we also ruled out 5, so as long as the calculation to One-fifth is good ....

After rapid adjustment, the efficiency is greatly improved!!!! I am mighty ...

But, so in 2\3\5 three prime numbers, the code will judge a composite number, so you need to make up one more sentence.

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

Someone else's way

Then I can not think of the optimization method ... So, I searched and found the following solution, I was stunned!!!!!

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

The use of the regular method, is really short ah, but I can see the yarn I understand!!!

I really do not understand what this principle, I then measured, and found that my code is far more efficient than this code. Thus, my method is still very excellent!!

My code requires 1600ms of all prime numbers within 100000 and this code requires 160000MS, which means that my code takes 1% of the time.

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

Add

I looked at some of the relevant information, as if the way I used the NUM/5 is not very good (the result is not wrong). A better way to do this is to use MATH.SQRT (num) to find the square root.

The test results for my code are as follows

As shown in the figure above, the results of my code are completely correct. But it was 1638 milliseconds. This is still true after many tests.

Square root method Test results are as follows

As shown in the figure above, this method is more scientific, faster, and tested more than 1150 milliseconds to 1250 milliseconds. Compared to my code performance, it's about 25%.

I am also determining whether the number of digits is even or 5, but also the judge can add up to be divisible by 3, toss half a day. I'm sure I want to reduce the amount of computing. But the code itself is also computational. I'll take my code out and look at it.

Performance has been improved Ah, it seems that my calculations are all negative optimization ah!

Finally, 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: It's totally my arithmetic bad cause I was in front of all kinds of smart. But it's also good to Practice tips-_-| | |

And finally, how long does it take to calculate all the primes within 1 million?

The above is a small set to introduce the JavaScript to determine whether the number of numbers is a summary of the method, I hope to help.

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.