help with prime pairs code
Salih Dincer
salihdb at hotmail.com
Wed Feb 19 23:58:09 UTC 2025
On Friday, 31 January 2025 at 20:05:54 UTC, Jabari Zakiya wrote:
> I'm converting Ruby code to D and am running into issues.
> Would appreciate what needs to be done to get it to compile/run
> correctly.
First of all, I see that you don't use reserve() at all in
arrays. Since I work on a mobile platform (by Dcoder from India),
I have limited opportunities. So would you try the code below;
does it work quickly, safely and with accurate results.
```d
import std.stdio, std.conv, std.range, std.algorithm;
import std.datetime.stopwatch : StopWatch;
void main(string[] args)
{
alias T = uint;
auto inputs = ["5_005_446", "65_537"];
auto nums = inputs.map!(i => i.filter!(n => n != '_'));
auto n = nums.map!(f => f.to!T())[0];
auto timer = StopWatch();
timer.start();
n.prime_pairs_lohi();
timer.peek.writeln();
}
void prime_pairs_lohi(T)(T n)
{
if (n & 1 || n < 4) { return writeln("Input not even n > 2"); }
if (n <= 6) { writeln([n, 1]); writeln([n/2, n/2]);
writeln([n/2, n/2]); return; }
T ndiv2 = n / 2;
T rhi = n - 2;
T[] lhr;// = iota(3, ndiv2, 2).filter!(e => gcd(e, n) ==
1).array;/*
lhr.reserve(n / 4); // SDB at 79 added!
auto factors = n.getFactors!100;
for (T i = 3; i < ndiv2; i += 2)
{
bool coprime = true;
foreach (p; factors)
{
if (i % p == 0)
{
coprime = false;
break;
}
}
if (coprime) lhr ~= i;
}//*/
// identify and store all powers and cross-products of the lhr
members < n-2
T[] lhr_del; // lhr multiples, not part of
a pcp
lhr_del.reserve(n / 2); // SDB at 79 added!
foreach(i, r; lhr) { // iterate thru lhr to find
prime multiples
auto rmax = rhi / r; // ri can't multiply r with
values > this
if (r < rmax) lhr_del ~= (r*r < ndiv2) ? r*r : n - r*r; //
for r^2 multiples
if (lhr[i+1] > rmax) break; // exit if product of
consecutive r’s > n-2
foreach(ri; lhr[i+1..$]) { // for each residue in
reduced list
if (ri > rmax) break; // exit for r if
cross-product with ri > n-2
lhr_del ~= (r*ri < ndiv2) ? r*ri : n - r*ri; //
store value if < n-2
} }
// remove from lhr its lhr multiples, the pcp remain
lhr_del.sort!"a < b";
lhr = setDifference(lhr, lhr_del).array;
writeln([n, lhr.length]); // show n and pcp prime pairs
count
writeln([lhr[0], n-lhr[0]]); // show first pcp prime pair
of n
writeln([lhr[$-1],n-lhr[$-1]]); // show last pcp prime pair
of n
}
auto getFactors(int limit, T)(T n)
{
T[] factors;
T f = 3;
T x = n;/*
T x = n;
while (x % 2 == 0) {
factors ~= 2;
x /= 2;
}//*/
while (f < limit && f * f <= x)
{
if (x % f == 0)
{
if (!factors.canFind(f))
{
factors ~= f;
}
x /= f;
} else {
f += 2;
}
}
//if (x > 1) factors ~= x;
return factors;
}
auto gcd(T)(T a, T b)
{
while (b != 0)
{
auto temp = b;
//while (a >= b) a -= b;/*
a %= b; //*/
b = a;
a = temp;
}
return cast(T)a;
}
```
SDB at 79
More information about the Digitalmars-d-learn
mailing list