Centered Square Numbers follow the function f(x) = x^2 + (x+1)^2. Not all Centered
Square Numbers are prime number, so Centered Square Numbers which are prime fall under
a special classification called Centered Square Primes.
In this example I demonstrate how to apply the aforementioned mathematical function.
I also demonstrate how to adapt the "primes" function from the Prime Numbers sample
to simply allow the function to determine whether a number is prime (as opposed to
listing the first Nth prime numbers).
The two previously mentioned functions work together to find Centered Square Primes.
First, Centered Square Numbers are found incrementally. Each Centered Square Number is
tested for primality in turn. If the Centered Square Number is also a prime number, then
the number is printed to the screen. Otherwise, the number is not printed to the screen
and the program simply moves on to the next Centered Square Number.
Let's look at some code that finds the first n Centered Square Primes.
//includes
#include <iostream>
//namespace
using std::cin;
using std::cout;
using std::endl;
//forward declarations
void getCenteredSquarePrimes(int n);
int getCenteredSquareNumber(int x);
bool isPrime(int x);
//MAIN FUNCTION
int main(){
//for user input
int n;
//prompt user for input
cout << "How many Centered Square Primes do you wish to List? ";
cin >> n;
//list centered square prime numbers
getCenteredSquarePrimes(n);
cout << endl;
//pause console
system("pause");
//exit
return 0;
}
//getCenteredSquarePrimes
//lists the first n centered square prime numbers
void getCenteredSquarePrimes(int n){
//local variables
int discoveredCSPs = 0; //number of centered square primes currently listed
int CSN; //output of centered square function f(x) = x^2 + (x+1)^2
int x = 1; //x for f(x)
//loop until number of listed CSPs matches user input
while(discoveredCSPs < n){
//set CSN to f(x) = x^2 + (x+1)^2
CSN = getCenteredSquareNumber(x);
//test CSN for primality
if(isPrime(CSN) == true){
//if CSN is prime, print it to the console and increment number of listed CSPs
cout << CSN << " ";
discoveredCSPs++;
}
//increment x for f(x)
x++;
}
}
//getCenteredSquareNumber
//returns f(x) = x^2 + (x+1)^2
int getCenteredSquareNumber(int x){
return ((x*x)+((x+1)*(x+1)));
}
//isPrime
//tests x for primality
//this function has been adapted from the Prime Numbers sample
bool isPrime(int x){
//numbers to test for primeness and to test with
int currentNumber = x;
int currentDivisor = 2;
int threshold = currentNumber/currentDivisor;
//loop to for primality
while(true){
if(currentDivisor == currentNumber  currentDivisor >= threshold){
//currentNumber is prime, print it to console
return true;
} else if((currentNumber % currentDivisor) == 0){
//currentNumber is not a prime, do not print it
return false;
} else {
//move to next divisor
threshold = (currentNumber/currentDivisor)+1;
currentDivisor++;
}
}
//return a bool for all control paths
return false;
}
