C++ Prime Number
A Prime number is a mathematical number that can be divisible by itself and by 1. Prime numbers though can get difficult to code efficiently, because of the process it takes to calculate them. The following is a very efficient algorithm for calculating C++ prime numbers.
Usually people who try to code a prime number algorithm in C++ or C, will loop through each number, and in the inner loop divide by two to check the prime number conditions. This is inefficient, why bother checking each number when prime numbers cannot be even except 2? You can also use sqrt function in math.h instead of divide by 2.
The following algorithm takes about 0.011 seconds to generate 100 prime numbers.
#include <math.h>
using namespace std;
int main(){
int prime(1); // start from 3
int d, counter(0);
bool bPrime = true;
cout << "ID Prime Numbers:\n" << 2 << endl; // print 2, because we skip even numbers
int max = 100; // max numbers
for( ;prime < max-1; ){ // infinite loop condition is prime less than max-1
prime += 2; // ignore even numbers
for(d = 3; d <= ((int)floor(sqrt(prime))); d += 2){
if(((prime%d) == 0) && (prime != d)){
bPrime = false; // not a prime number so set to false
break; // escape from this loop
}
}
if(bPrime){
cout << prime << endl;
counter++;
}
bPrime = true;
}
cout << counter << " prime numbers out of " << prime << " numbers\n";
cout << "If you have problems, join ID forums: http://www.infernodevelopment.com/forum\n";
return 0;
}
I loop through 100 prime numbers, incrementing counter if we find a prime number, and increasing prime by 2 each loop (to avoid even numbers).
The inner loop checks for remainders, if there is a remainder and the divisor is not the same number as prime then it is a prime number.
This seems to work accurately and efficiently. If you don't know how to make this program, just download Code::Blocks.
Post new comment