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

Function isPrime

Exercises/Modules/Chapter 08/Soln8_05.cpp:56–71  ·  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

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

Callers 1

filterPrimeNumbersFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected