0
I want to write a code to check if a given number is Prime or not.
2 odpowiedzi
+ 2
Cohen, you can stop the loop after testing the square root of the number, because if the number has factors higher than its square root, the other factors are always lower and have already been tested by that point.
Also, some small tips: you can announce that the number is prime after the for loop ends (instead of checking if i equals num at each loop), and put "return 0" after stating that the number is prime or not.
+ 1
I've already made one, check it out☺
http://code.sololearn.com/czA6HgQEsP8B/#cpp
It just goes through a for loop, checking whether the input number is divisible by anything other than 1 or itself. If it is divisible, then the output is not prime, and the loop breaks. If the for loop successfuly reaches the end, it means that it found no divisible numbers, thus the number is prime.
If the number is less than or equal to 1, it straight away prints not prime, as the for loop will not print anything for these numbers, as the for loop starts on 2.