-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathprimitive_sum_of_two_squares.pl
executable file
·73 lines (58 loc) · 1.35 KB
/
primitive_sum_of_two_squares.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/perl
# Daniel "Trizen" Șuteu
# Date: 24 October 2017
# https://github.com/trizen
# Find a solution to x^2 + y^2 = n, for numbers `n` whose prime divisors are
# all congruent to 1 mod 4, with the exception of at most a single factor of 2.
# Blog post:
# https://trizenx.blogspot.com/2017/10/representing-integers-as-sum-of-two.html
# See also:
# https://oeis.org/A008784
use 5.020;
use strict;
use warnings;
use ntheory qw(sqrtmod);
use experimental qw(signatures);
sub primitive_sum_of_two_squares ($p) {
if ($p == 2) {
return (1, 1);
}
my $s = sqrtmod($p - 1, $p) || return;
my $q = $p;
while ($s * $s > $p) {
($s, $q) = ($q % $s, $s);
}
return ($s, $q % $s);
}
foreach my $n (1 .. 100) {
my ($x, $y) = primitive_sum_of_two_squares($n);
if (defined($x) and defined($y)) {
say "f($n) = $x^2 + $y^2";
if ($n != $x**2 + $y**2) {
die "error for $n";
}
}
}
__END__
f(2) = 1^2 + 1^2
f(5) = 2^2 + 1^2
f(10) = 3^2 + 1^2
f(13) = 3^2 + 2^2
f(17) = 4^2 + 1^2
f(25) = 4^2 + 3^2
f(26) = 5^2 + 1^2
f(29) = 5^2 + 2^2
f(34) = 5^2 + 3^2
f(37) = 6^2 + 1^2
f(41) = 5^2 + 4^2
f(50) = 7^2 + 1^2
f(53) = 7^2 + 2^2
f(58) = 7^2 + 3^2
f(61) = 6^2 + 5^2
f(65) = 8^2 + 1^2
f(73) = 8^2 + 3^2
f(74) = 7^2 + 5^2
f(82) = 9^2 + 1^2
f(85) = 7^2 + 6^2
f(89) = 8^2 + 5^2
f(97) = 9^2 + 4^2