+ 6

Prime number detection

Is there any other way than 'if' to check if an integer is a prime number ?? I really do not know :((( https://code.sololearn.com/coRv4LTTdQBh/?ref=app

20th Nov 2019, 4:38 AM
Phuong Pham
Phuong Pham - avatar
9 Answers
+ 15
Phuong Pham The program can accelerated a little if noticed that all prime numbers are larger than 2 and 3 in the form 6kāˆ’1 or 6k+1, where kā‰„1 ( of course, the opposite is not true ). Indeed, the numbers of 6k, 6k+2 and 6k+4 are certainly even, divisible by 2, the numbers of the forms 6k+3 are divisible by 3, so the only remaining ones are 6k+1 and 6k+5, the latter being certainly 6kā€²āˆ’1 ( for kā€²=k+1 ). So instead of checking divisibility with all odd numbers smaller than the root, we can check divisibility with all 6kāˆ’1 or 6k+1 numbers, thus avoiding one with every three odd numbers and speeding up the program so. if (n == 1 || (n % 2 == 0 && n != 2) || (n % 3 == 0 && n != 3)) return false; for (int k=1; (6*k -1)*(6*k -1)<=n; k++){ if (n % (6*k +1) == 0 || n % (6*k -1) == 0) return false; } return true; Ace Please, Can you check this one: ā€¢ https://code.sololearn.com/c91941ZiLAdL/?ref=app
20th Nov 2019, 8:05 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 14
Phuong Pham Thank you! šŸ˜Š Sorry, I didn't mention, I wrote an addition for Ace's solution above.šŸ‘ [ Edited: ] here's another one, you can play around and practicingšŸ‘ https://code.sololearn.com/cWcAymcKrid0/?ref=app
20th Nov 2019, 8:35 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 9
I still recognize you. This is not the first time you helped me. You are really enthusiastic and kind. Your explanation will help me a lot. Thanks for your help and compliments :))
20th Nov 2019, 5:08 AM
Phuong Pham
Phuong Pham - avatar
+ 2
Danijel lvanovĆ­c Good code. Thank you very much šŸ˜
20th Nov 2019, 8:28 AM
Phuong Pham
Phuong Pham - avatar
+ 2
https://code.sololearn.com/c9C3YT2h8xD8/?ref=app here flag is used for the same purpose as litmus paper is used in chemistry experiments and the loop starts from 2 and checks till given_numner(p) /2 the loop breaks once it finds the given number is composite it doesn't check further and is thus time saving šŸ˜Š
21st Nov 2019, 2:39 AM
Aditya
Aditya - avatar
+ 1
Anthony Short and effective code is one of the top criteria when I program. I really like your code. Thanks for your interest in this questionā¤
21st Nov 2019, 6:05 AM
Phuong Pham
Phuong Pham - avatar
+ 1
this prime number haunted me a lot when I was small now I feel myself defeating my fear thanks to your compliment Phuong Pham
21st Nov 2019, 8:23 AM
Aditya
Aditya - avatar
0
Anthony Don't be so modest. Have a nice day šŸ˜†
24th Nov 2019, 9:13 AM
Phuong Pham
Phuong Pham - avatar