Humm.. It's not very efficient. As prime numbers cannot be even, why test every even number in the loop? You can just test if divisible by 2 at the beginning and then start the loop at 3 and increment by 2. Also, there's no need to test all numbers up to the one being tested. As a number squared is divisible by the number, the loop test can stop at the square root of the tested number.
Why not use the IsPrime function in GetPrimes rather than repeat the same code twice? Also passing the vector by reference is more efficient than returning a vector.Code://A Prime Number can be divided evenly only by 1, or itself //So if a number(n) can be divided by any number between 2 and n-1 inclusive then it is not prime //An even number is never prime bool IsPrime(int num) { //numbers 1 and 2 are defined as prime if ((num == 1) || (num == 2)) return true; //Even numbers are never prime if ((num % 2) == 0) return false; const int limit = (const int)sqrt((double)num); //Need only consider odd numbers before sqrt for (int i = 3; i <= limit; i += 2) if ((num % i) == 0) return false; // not prime return true; }
Again, with ReverseInteger, there is a much more efficient method without the overhead of converting to and from a stringCode:typedef vector<int> PRIMES; //Put the first N prime numbers into a vector void GetPrimes(PRIMES& vp, int no) { int prime = 3, //Start primes at 3 fnd = 0; //Number found while (fnd <= no) { if (IsPrime(prime)) { vp.push_back(prime); //Save prime fnd++; } prime +=2; //Only odd numbers } return; }
Code://Reverse an integer int ReverseInteger(int no) { int rnum = 0; while (no) { rnum = rnum * 10 + (no % 10); no /= 10; } return rnum; }
So the main program now looks like
Code:int main() { int num, prime, rprime; PRIMES Vp; cout << "Enter number of primes to check for emirp status: "; cin >> num; GetPrimes(Vp, num); const size_t noprimes = Vp.size(); for (size_t i = 0; i < noprimes; i++) { prime = Vp[i]; rprime = ReverseInteger(prime); cout << prime << " is prime "; if (IsPrime(rprime)) { cout << "and " << rprime << " is prime so " << prime << " is emirp " << endl; } else { cout << "but " << rprime << " is not prime so " << prime << " is not emirp " << endl; } } return 0; }




Reply With Quote