Answer 1, authority 100%
Write something as
int n;
// enter n from keyboard
for (i = 2; i & lt; sqrt (n); i ++) {
if (n% i == 0) {
// deduce that n is not prime, since it is divisible by i
return 0;
}
}
// print that n is prime.
return 0;
The algorithm, of course, can be significantly accelerated, at least twice, but enough for a start.
Answer 2, authority 25%
And you can check divisibility by prime numbers …
And finding them in a small amount will not be difficult … =)
Sieve of Eratosthenes (to the root of n). Finds numbers up to 10 ^ 7 in 1 second about …
And then an enumeration of divisibility (Or if the number has already been found by Eratosthenes, then there is no need to iterate over) into prime numbers, if the number is greater than 10 ^ 7 also up to the root of n …
Answer 3
Answer 4
Something like this:
bool prime (ll n) {
for (ll i = 2; i & lt; = sqrt (n); i ++) {
if (n% i == 0)
return false;
}
return true;
}
Answer 5
# include & lt; iostream & gt;
#include & lt; cmath & gt;
using namespace std;
int main () {
int n, i;
bool isPrime = true;
cout & lt; & lt; "Enter a number:";
cin & gt; & gt; n;
cout & lt; & lt; n & lt; & lt; endl;
for (i = 2; i & lt; = (sqrt (abs (n))); i ++) {
if (n% i == 0) {
isPrime = false;
break;
}
}
if (isPrime)
cout & lt; & lt; "This is a prime number" & lt; & lt; endl;
else
cout & lt; & lt; "This is not a prime number" & lt; & lt; endl;
return 0;
}
This is the finished code
Answer 6
I’m happy with the old topic, but I’ll add it anyway. There is one peculiarity of primes – when squaring a number, dividing this number squared by 24 will give a remainder of 1 (c 2 and 3 does not work, because they are too small, but with the rest of the numbers it works fine and does not waste a lot of resources for checks)
int isprime (int num)
{
if ((num * num)% 24 == 1)
{
return true;
}
return false;
}
Answer 7
The first answer is inaccurate !!!
I would write like this
bool prostoNumer (int n) {
for (int i = 2; i & lt; = sqrt (n); i ++)
if (n% i == 0)
return false;
return true;
}
PS: the point is that it skips 4. Because the loop doesn’t work sqrt (4) == 2, 2 & lt; 2 and therefore the loop exits with a false result. need to fix 2 & lt; = 2