Gaussian Primes > is_prime function

Hi.

I'm having some trouble modifying an is_prime() function to accept only Gaussian primes.

The three conditions I need to incorporate (for a+bi) are:
(1) if a=o && b=4n+3
(2) if b=0 && a=4n
(3) if a^2 + b^2 is a general prime number

I know that I need to add conditions that if any of these three conditions are met, then the compiler should return 'true' and then output the values in a vector. And I know that I need to add these conditions as loops, I'm just not sure how to add the condition involving 4n+3.

Here's what I'm trying to modify, any help would be great!

#include <iostream>
#include <vector>

using namespace std;

bool is_prime(long);

int main()
{

long N_MAX;
cout << "Enter a value for N_MAX : "; cin>>N_MAX;

vector<long> primes(N_MAX);

short ctr_primes = 0;
long n = 2;

while( ctr_primes<N_MAX )
{
if ( is_prime(n) )
{
primes[ctr_primes]=n;
ctr_primes++;
}
n++;
}

for(int i=0; i<N_MAX; i++)
cout << "Prime #" << i+1 << " is " << primes[i] << endl;

return 0;
}

bool is_prime(long p)
{
if( p<2 ) return false;

for(int i=2; i*i<=p; i++)
if ( p%i==0 )
return false;

return true;
}
> I'm having some trouble modifying an is_prime() function to accept only Gaussian primes.


Don't modify is_prime(). Write a new function is_gausian_prime() which uses is_prime().

> I'm just not sure how to add the condition involving 4n+3.

if a == 4n + 3, then a%4 == 3.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <complex>
#include <cstdlib>

bool is_prime( long n ) ;

bool is_4n_plus_3( long a ) { return a%4 == 3 ; }

bool is_gausian_prime( std::complex<long> z ) // a + bi
{
    const long a = std::abs( z.real() ) ;
    const long b = std::abs( z.imag() ) ;

    if( a == 0 ) return is_prime(b) && is_4n_plus_3(b) ;
    else if( b == 0 ) return is_prime(a) && is_4n_plus_3(a) ;
    else return is_prime( a*a + b*b ) ;
}
Topic archived. No new replies allowed.