0
I have a prime.cpp project. Can I write shorter than this code?
2 Réponses
+ 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;
}
+ 3
Yes. Once i*i is greater than val, it must be prime.