How to resolve the algorithm Gaussian primes step by step in the Perl programming language
How to resolve the algorithm Gaussian primes step by step in the Perl programming language
Table of Contents
Problem Statement
A Gaussian Integer is a complex number such that its real and imaginary parts are both integers. The norm of a Gaussian integer is its product with its conjugate.
A Gaussian integer is a Gaussian prime if and only if either: both a and b are non-zero and its norm is a prime number, or, one of a or b is zero and it is the product of a unit (±1, ±i) and a prime integer of the form 4n + 3. Prime integers that are not of the form 4n + 3 can be factored into a Gaussian integer and its complex conjugate so are not a Gaussian prime. Gaussian primes are octogonally symmetrical on a real / imaginary Cartesian field. If a particular complex norm a² + b² is prime, since addition is commutative, b² + a² is also prime, as are the complex conjugates and negated instances of both.
Find and show, here on this page, the Gaussian primes with a norm of less than 100, (within a radius of 10 from the origin 0 + 0i on a complex plane.) Plot the points corresponding to the Gaussian primes on a Cartesian real / imaginary plane at least up to a radius of 50.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Gaussian primes step by step in the Perl programming language
Source code in the perl programming language
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Gaussian_primes
use warnings;
use ntheory qw( is_prime );
my ($plot, @primes) = gaussianprimes(10);
print "Primes within 10\n", join(', ', @primes) =~ s/.{94}\K /\n/gr;
($plot, @primes) = gaussianprimes(50);
print "\n\nPlot within 50\n$plot";
sub gaussianprimes
{
my $size = shift;
my $plot = ( ' ' x (2 * $size + 1) . "\n" ) x (2 * $size + 1);
my @primes;
for my $A ( -$size .. $size )
{
my $limit = int sqrt $size**2 - $A**2;
for my $B ( -$limit .. $limit )
{
my $norm = $A**2 + $B**2;
if ( is_prime( $norm )
or ( $A==0 && is_prime(abs $B) && (abs($B)-3)%4 == 0)
or ( $B==0 && is_prime(abs $A) && (abs($A)-3)%4 == 0) )
{
push @primes, sprintf("%2d%2di", $A, $B) =~ s/ (\di)/+$1/r;
substr $plot, ($B + $size + 1) * (2 * $size + 2) + $A + $size + 1, 1, 'X';
}
}
}
return $plot, @primes;
}
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the Nim programming language
You may also check:How to resolve the algorithm Pythagorean triples step by step in the Wren programming language
You may also check:How to resolve the algorithm Hello world/Line printer step by step in the Prolog programming language
You may also check:How to resolve the algorithm Symmetric difference step by step in the Miranda programming language