Hi folks,

Big numbers are awesome!

In this tutorial we are going to calculate the largest known prime, as of August 2018: 277,232,917-1. And we are going to use GMP – GNU Multiple Precision Arithmetic Library – for that. And, yes we will write this program in pure C.

Here’s the code. I wrote comments on the code, so it is pretty much self-explanatory.

largest_known_prime.c

/* This program is licensed under the GNU GPLv3 or later */ /* Compile using: gcc largest_known_prime.c -o largest_prime -lgmp */ /* The largest known Marsenne prime is 2^77,232,917−1 as of August 2018 */ #include <gmp.h> #include <stdio.h> int main(int argc, char * argv[]) { mpz_t a; /* declare bignum 'a' */ int base, exponent; mpz_init(a); /* initialize a */ base = 2; exponent = 77232917; mpz_ui_pow_ui (a, base, exponent); /* a = base ^ exponent */ mpz_sub_ui(a,a,1); /* a = a - 1 */ mpz_out_str(stdout,10,a); /* output c in base 10 */ mpz_clear(a); /* delete variable 'a' from memory */ return 0; }

Compile the code using

gcc largest_known_prime.c -o largest_prime -lgmp

Run the binary file:

./largest_prime

or run it while directing the output to a text file:

./largest_prime > largest_known_prime.txt

Using the tee command, you can direct the output of the program to a text file, while simultaneously display it on screen:

./largest_prime | tee largest_known_prime.txt

In addition, you can measure how long it takes to run your program by using the command time :

time ./largest_prime

In my case, I get:

real 0m8,237s user 0m5,647s sys 0m0,148s

In less than 10 seconds, GMP calculated this beast of a number! We can see that our computation finishes in:

9614659217371136582730618069762179071

which matches the result shown in wikipedia, so this means the result is most likely correct!

One funky remark: GMP let us output the result in numerical bases other than 10. For example: to see the same result in base 36 (10 numbers + 26 letters), we change the corresponding line in the code to

mpz_out_str(stdout,36,a);

then save the file, compile the code and run it again. We get the last digits of the result:

aacjqobt1cvb8b02jqu9abxi5hw7rhxt1x2xmrlkv

Isn’t that cool? Now the best of having an alphanumerical representation of the number is that we can search for particular sequences of characters. For example:

grep "best" -o largest_known_prime.txt | wc -l

outputs 13 occurrences of the word “best” in the result alphanumeric number. You can display n characters (say 10) of the sequence before and after the matches by issuing:

grep -E -o ".{0,10}best.{0,10}" largest_known_prime.txt

For example, the last occurrence takes place within the following sequence:

6kerseiil1best5ch8wm5nkc

I am sure you can find more interesting words to search for though… 😉

Ok, stay in tune! Check out my GMP examples repository. If there is any example you would like me to write about, let us known in the comments section below!

Thanks for reading!