0

I have a prime.cpp project. Can I write shorter than this code?

https://code.sololearn.com/cnpS06z4qWfh/?ref=app

16th Mar 2018, 2:26 PM
RainStorm
RainStorm - avatar
2 Answers
+ 2
//Maybe like this it might have some small improvements. // primenumber.cpp #include <iostream> using namespace std; bool prime(int); int main() { int num; try{ if(!(cin >> num)) throw "Invalid input"; if(num < 0) throw "Number less then zero"; cout << (prime(num)? "Yes" : "No"); }catch(const char *str) { cout << str; } } bool prime (int val) { if(val <= 3 && val > 1) return true; if(!(val % 2)) return false; for(int i = 3;i * i <= val; i += 2) if(!(val % i)) return false; return true; }
16th Mar 2018, 11:46 PM
Timon Paßlick
+ 3
Yes. Once i*i is greater than val, it must be prime.
16th Mar 2018, 2:31 PM
John Wells
John Wells - avatar