Last active
April 9, 2022 10:18
-
-
Save iBug/ddd20dbdd527a333441a10446324ffe3 to your computer and use it in GitHub Desktop.
Quick Mersenne Prime test using Lucas-Lehmer method and GMP library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <math.h> | |
| #include <gmp.h> | |
| int test_p(int p) { | |
| if (p % 2 == 0) | |
| return 0; | |
| for (int i = 3; i <= sqrt(p); i += 2) | |
| if (p % i == 0) | |
| return 0; | |
| return 1; | |
| } | |
| void test_mp(int p) { | |
| if (p == 1) | |
| return; | |
| if (p == 2) { | |
| printf("2 3\n"); | |
| return; | |
| } | |
| if (!test_p(p)) { | |
| return; | |
| } | |
| mpz_t mp, s; | |
| mpz_init_set_ui(mp, 1); | |
| mpz_mul_2exp(mp, mp, p); | |
| mpz_sub_ui(mp, mp, 1); | |
| mpz_init_set_ui(s, 4); | |
| for (int i = 0; i < p - 2; i++) { | |
| mpz_mul(s, s, s); | |
| mpz_sub_ui(s, s, 2); | |
| mpz_mod(s, s, mp); | |
| } | |
| mpz_t r; | |
| mpz_init(r); | |
| mpz_mod(r, s, mp); | |
| if (mpz_sgn(r) == 0) { | |
| printf("%d ", p); | |
| mpz_out_str(stdout, 10, mp); | |
| printf("\n"); | |
| } | |
| mpz_clear(r); | |
| mpz_clear(s); | |
| mpz_clear(mp); | |
| } | |
| int main() { | |
| for (int i = 1; i < 1000; i++) { | |
| test_mp(i); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment