MCPcopy Create free account
hub / github.com/Apress/beginning-cpp20 / isPrime

Function isPrime

Exercises/NoModules/Chapter 08/Soln8_05.cpp:55–70  ·  view source on GitHub ↗

The sqrt() in the for loop below is not required. The following loop would be equally correct, just a bit slower: for (unsigned i = 2; i < number; ++i) { ... } It is a quite common optimisation though to stop testing at the square root of the number. Think about why this is correct! */

Source from the content-addressed store, hash-verified

53 the square root of the number. Think about why this is correct!
54*/
55bool isPrime(unsigned number)
56{
57 // a prime number is a natural number strictly greater than 1...
58 if (number <= 1) return false;
59
60 // ...and with no positive divisors other than 1 and itself
61 for (unsigned i{ 2 }; i < std::sqrt(number); ++i)
62 {
63 if (number % i == 0)
64 {
65 return false;
66 }
67 }
68
69 return true;
70}
71
72std::vector<unsigned> generateNumbers(unsigned to, unsigned from)
73{

Callers 1

filterPrimeNumbersFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected