Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Last active January 30, 2016 09:59
Show Gist options
  • Save alphaKAI/5135b30686ce5289376e to your computer and use it in GitHub Desktop.
Save alphaKAI/5135b30686ce5289376e to your computer and use it in GitHub Desktop.
Project Euler - Problem 3 in D
import std.algorithm,
std.random,
std.range,
std.stdio;
R delegate(Args) Z(R, Args...)(R delegate(R delegate(Args), Args) f){
return (Args args) => f(Z(f), args);
}
void main() {
(N =>
(getRand =>
(mr_prime =>
(rho_find_pd =>
(rho_prime_division =>
rho_prime_division(N, false).join.sort!"a>b".uniq.array[0]
)(Z((ulong[][] delegate(ulong, bool) rho_prime_division, ulong n, bool suppress_sort) =>
mr_prime(n) ?
[[n, 1]]
: (d =>
(ulong[][] res) {
foreach (arr; rho_prime_division(d, true)) {
(cnt =>
(q, k) {
while (n % q == 0) {
n /= q;
cnt++;
}
res ~= [q, cnt];
}(arr[0], arr[1])
)(0);
}
res ~= rho_prime_division(n, true);
return suppress_sort ? res : res.sort.array;
}([[]])
)(rho_find_pd(n))
))
)((ulong n) =>
(gcd =>
(f_gen =>
(k) {
foreach (_; k.iota) {
return ((ulong delegate(ulong) f) =>
((ulong d, ulong x, ulong y) {
while (d == 1) {
x = f(x);
y = f(f(y));
d = gcd(n, (z => z < 0 ? z * -1 : z)(x - y));
}
return d < n ? d : n;
})(1, 2, 2)
)(f_gen());
}
return true;
}(3)
)(() =>
(c) {
while(!(c != 0 && c != n - 2)) {
c = getRand() % n;
}
return ((ulong x) => (x * x + c) % n);
}(getRand() % n)
)
)(Z((ulong delegate(ulong, ulong) gcd, ulong a, ulong b) => b ? gcd(b, a%b) : a < 0 ? a * -1 : a))
)
)((ulong n) =>
(mod_pow =>
(_d =>
(d =>
(k) {
foreach(_; k.iota) {
if (!
(a =>
(t =>
(y) {
while (t != n-1 && y != 1 && y != n-1) {
y = (y * y) % n;
t <<= 1;
}
if (y != n - 1 && (t & 1) == 0) {
return false;
} else {
return true;
}
}(mod_pow(a, t, n))
)(d)
)(getRand() % (n - 1) + 1)) {
return false;
}
}
return true;
}(20)
)((d) {
while((d & 1) == 0) {
d >>= 1;
}
return d;
}(_d))
)(n - 1)
)((ulong base, ulong pwr, ulong mod) =>
(ulong r) {
while (pwr > 0) {
if((pwr & 1) == 1) {
r = (r * base) % mod;
}
base = (base * base) % mod;
pwr >>= 1;
}
return r;
}(1)
)
)
)((){
Mt19937 gen;
return gen.seed(unpredictableSeed), gen.front;
})
)(600851475143).writeln;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment