"Prime number" to judge prime numbers (faster method C++)

Preface

  to be honest, I feel that I have also brushed 1,200 questions, and some questions have been brushed again and again, but there are still yes or no, and no or no. So I thought about whether there was a problem with my question-making mode. The following shows my previous style of doing questions,

Hey, I still follow the old path of senior third, which is to brush the questions, not to summarize, not to classify, only to pursue the quantity. In order to improve this situation, I decided to summarize and classify in order to make progress.

Theme:

bool isPrime(int a) {
    if(a == 1) return 0;
    if(a == 2 || a == 3) return 1;
    if(a%6 != 1 && a%6 != 5) return 0;
    int sqrtA = sqrt(a);
    for(int i = 5; i <= sqrtA; i += 6) {
        if(!(a%i)|| !(a%(i+2))) return 0;
    }
    return 1;
}

  Thinking analysis: The rule is to classify the numbers greater than or equal to 5 by %6, there will be 6 cases where the remainder is 0, 1, 2, 3, 4, and 5, among these six cases, 0, 2, 3, 4 are not acceptable Yes, there are evenly divisible numbers, and only 1, 5 is satisfied, then the type of numbers with the remainder of 1, 5 are recorded as type A for judgment, as long as they are not divisible by the number of type A smaller than themselves, you can Explain that this number is prime. The time complexity (sqrt(n)/3) is equivalent to only judging a number less than 1/3 of sqrt(n).

Thinking:

  Thinking before doing things will save time in most cases!

Guess you like

Origin blog.csdn.net/Look_star/article/details/109190923