- Fixed function argument (should be signed)
- Check only uneven numbers in the main loop and treat mod 2 as a special case.
- Removed useless cast.
class PrimeNumber { public: // Check if given number is prime or not. static bool isPrime(long long num) { if (num <= 1) return false; if (num == 2) return true; if (num % 2 == 0) return false; for (long long i = 3; i * i <= num; i += 2) if (num % i == 0) return false; return true; } };
- class PrimeNumber {
- public:
- // Check if given number is prime or not.
static bool isPrime(unsigned long long num ) {if(num <= 1) return false;for( long long i = 2; (long long) i * i <= num; i++)if( num % i == 0) return false;- static bool isPrime(long long num) {
- if (num <= 1) return false;
- if (num == 2) return true;
- if (num % 2 == 0) return false;
- for (long long i = 3; i * i <= num; i += 2)
- if (num % i == 0) return false;
- return true;
- }
- };
Describe(PrimeNumber_TestIsPrime) { It(TestIsPrimeSmall) { Assert::That(false, Equals(PrimeNumber::isPrime(-1))); Assert::That(false, Equals(PrimeNumber::isPrime(0))); Assert::That(false, Equals(PrimeNumber::isPrime(1))); Assert::That(true, Equals(PrimeNumber::isPrime(2))); Assert::That(true, Equals(PrimeNumber::isPrime(3))); Assert::That(false, Equals(PrimeNumber::isPrime(4))); Assert::That(true, Equals(PrimeNumber::isPrime(5))); Assert::That(true, Equals(PrimeNumber::isPrime(11))); Assert::That(true, Equals(PrimeNumber::isPrime(57191))); } It(TestIsPrimeLarge) { Assert::That(true, Equals(PrimeNumber::isPrime(1000000007))); Assert::That(true, Equals(PrimeNumber::isPrime(2147483647))); Assert::That(true, Equals(PrimeNumber::isPrime(2305843009213693951))); } };
- Describe(PrimeNumber_TestIsPrime)
- {
- It(TestIsPrimeSmall)
- {
- Assert::That(false, Equals(PrimeNumber::isPrime(-1)));
- Assert::That(false, Equals(PrimeNumber::isPrime(0)));
- Assert::That(false, Equals(PrimeNumber::isPrime(1)));
Assert::That(false, Equals(PrimeNumber::isPrime(-1)));- Assert::That(true, Equals(PrimeNumber::isPrime(2)));
- Assert::That(true, Equals(PrimeNumber::isPrime(3)));
- Assert::That(false, Equals(PrimeNumber::isPrime(4)));
- Assert::That(true, Equals(PrimeNumber::isPrime(5)));
- Assert::That(true, Equals(PrimeNumber::isPrime(11)));
- Assert::That(true, Equals(PrimeNumber::isPrime(57191)));
- }
- It(TestIsPrimeLarge)
- {
- Assert::That(true, Equals(PrimeNumber::isPrime(1000000007)));
- Assert::That(true, Equals(PrimeNumber::isPrime(2147483647)));
// Takes longer than 12000ms to complete.//Assert::That(true, Equals(PrimeNumber::isPrime(2305843009213693951)));- Assert::That(true, Equals(PrimeNumber::isPrime(2305843009213693951)));
- }
- };