Check if a number is prime or not

PHOTO EMBED

Thu Jul 11 2024 02:51:16 GMT+0000 (Coordinated Universal Time)

Saved by @Xeno_SSY #c++

bool isprime(int x){
    if(x<=1) return false;
    if(x==2 || x==3) return true;
    if(x%2==0 || x%3==0) return false;
    for(int i=5;i*i<=x;i+=6){
        if(x%i==0 || x%(i+2)==0) return false;
    }
    return true;
}
content_copyCOPY

Any number greater than than 6 can be represented as 6k+1,2,3,4or5 6k , 6k+2,6k+4 are definitely not prime as they are even 6k +3 is not prime as it is divisible by 3 therefore we just need to check 6k+1 and 6k+5 i.e 6k+1 and 6k-1; initiating at i=5 and adding 6 can help achieve 6k-1, using n%(i+2) helps check the 6k+1 too using this approach is three times better than just incrementing i by 1