Skip to content

Instantly share code, notes, and snippets.

@Hermann-SW
Last active April 13, 2024 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hermann-SW/c870ca8352d1fcea60819102e88bbb49 to your computer and use it in GitHub Desktop.
Save Hermann-SW/c870ca8352d1fcea60819102e88bbb49 to your computer and use it in GitHub Desktop.
Fast libgmpxx implementation of 300 decimal digit factoring puzzle
/*
https://www.mersenneforum.org/showthread.php?t=29584
Factors 300 decimal digits semiprime n, knowing its prime factors consist of
digits 3 and 7 only, 10,000 times in less than 1s in total on 7950X CPU.
f=puzzle
g++ -O3 -Wall -Wextra -pedantic $f.cc -o $f -lgmp -lgmpxx
cpplint --filter=-legal/copyright,-runtime/references $f.cc
cppcheck --enable=all --suppress=missingIncludeSystem $f.cc --check-config
*/
#include <gmpxx.h>
#include <iostream>
mpz_class n = mpz_class("275749941173280562233206455736390095733872087404999918648104846244787100445192883149543759714060622705730237359190372814923054256546971783443405641914960603655306172124864651388859278743238322029857347654069385380300498785472834485212409650369402081148638740386329616025152776319904754759259065304901"); // NOLINT
void g(mpz_class& R,
mpz_class n, mpz_class a = 0, mpz_class b = 0, mpz_class m = 1) {
for (unsigned ad = 3; ad <= 7; ad += 4) {
for (unsigned bd = 3; bd <= 7; bd += 4) {
mpz_class d = n-(ad*b+bd*a+ad*bd*m);
if (d % 10 != 0) continue;
d /= 10;
if (d == 0) { R = a + ad * m; return; }
mpz_class A = a + m * ad;
mpz_class B = b + m * bd;
mpz_class M = m * 10;
g(R, d, A, B, M);
if (R != 0) return;
}
}
}
int main(void) {
clock_t start = clock();
for (int i = 0; i < 10000; ++i) {
mpz_class r = 0;
g(r, n);
}
std::cout << static_cast<float>(clock() - start) / CLOCKS_PER_SEC << "s\n";
mpz_class r = 0;
g(r, n);
std::cout << r << std::endl;
return 0;
}
@Hermann-SW
Copy link
Author

hermann@7950x:~$ f=puzzle 
hermann@7950x:~$ g++ -O3 -Wall -Wextra -pedantic $f.cc -o $f -lgmp -lgmpxx
hermann@7950x:~$ cpplint --filter=-legal/copyright,-runtime/references $f.cc
Done processing puzzle.cc
hermann@7950x:~$ cppcheck --enable=all --suppress=missingIncludeSystem $f.cc --check-config
Checking puzzle.cc ...
hermann@7950x:~$ ./puzzle 
0.980455s
737737733773377773337733777733777377737333773733377737737377373337377333733777373337373737777337777777333337337733773777737773777337777777773773373373
hermann@7950x:~$ 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment