Validating primes with regular expressions

Source: Internet
Author: User

Today we see this quite wonderful verification method, the original code is JS, but the algorithm for Py also applies.

The original code is as follows:

1 functionSS (d) {2     if(d <= 3) {3         return true;4     }5     //turn the value into 1116     varstr = ";7      while(--d >= 0) {8str + = 1;9     }TenConsole.log ("str:", str); One     return!/^ (11+?) \1+$/. Test (str) A } -  - //Test the  for(vari = 2; I < 100; i++) { -     if(SS (i)) { - Console.log (i) -     } +}

The experimental results show that the algorithm is effective indeed.

The algorithm actually refers to a string with a length equal to 1 for the number conversion, and then matches the string.

In non-greedy mode, the 11+ can match 11, or it can match to 111, and then by \1 the reverse reference, you can match both modes. These two modes are judged to be non-prime (the result of the regular test method is not), and the prime number is not satisfied.

The specific mathematical principles are not well understood at the moment and are recorded for additions.

The advantage of this algorithm is that it is not necessary to traverse the N/2 sequence sequentially, and it is very effective in the case of limited computational capacity. However, due to the need to build a string of numeric size length, if the value is too large, it consumes considerable memory and can cause memory overflow. Can be thought of as a solution for space-changing time.

Validating primes with regular expressions

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.