用GMP库实现大数运算的引子

CSDN论坛上有不少关于大数运算的问题,有用文件、数组和多项式等多种描述方式,作者觉得科学应该尽量建立在“巨人的肩膀上”,GMP库就是非常适合作大数运算的,其内涵还是引用原文来得给力一些。

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface.

The main target applications for GMP are cryptography applications and research, Internet security applications, algebra systems, computational algebra research, etc.

GMP is carefully designed to be as fast as possible, both for small operands and for huge operands. The speed is achieved by using fullwords as the basic arithmetic type, by using fast algorithms, with highly optimised assembly code for the most common inner loops for a lot of CPUs, and by a general emphasis on speed.

GMP is faster than any other bignum library. The advantage for GMP increases with the operand sizes for many operations, since GMP uses asymptotically faster algorithms.

The first GMP release was made in 1991. It is continually developed and maintained, with a new release about once a year.

GMP is distributed under the GNU LGPL. This license makes the library free to use, share, and improve, and allows you to pass on the result. The license gives freedoms, but also sets firm restrictions on the use with non-free programs.

GMP is part of the GNU project. For more information about the GNU project, please see the official GNU web site.

GMP's main target platforms are Unix-type systems, such as GNU/Linux, Solaris, HP-UX, Mac OS X/Darwin, BSD, AIX, etc. It also is known to work on Windows in both 32-bit and 64-bit mode.

GMP is brought to you by a team listed in the manual.

GMP is carefully developed and maintained, both technically and legally. We of course inspect and test contributed code carefully, but equally importantly we make sure we have the legal right to distribute the contributions, meaning users can safely use GMP. To achieve this, we will ask contributors to sign paperwork where they allow us to distribute their work. 

GMP用字符串来描述大数类型显得非常的自然,如有朋友确实有需要对大数运算作深入的研究,直接阅读GMP的源代码会更有实质上的收获,作者在这里只提供一段很小的应用代码,以抛砖引玉。

#include <stdio.h>
#include <gmp.h>

int main(int argc, char *argv[])
{
	mpz_t n;

	if(argc < 2)
	{
		printf("Usage: gmpcalc n\n");
		return -1;
	}

	/* 初始化10进制大整数n,并且把命令行的第一个参数赋值给它*/
	mpz_init(n);
	if(mpz_set_str(n, argv[1], 10) != 0)
		return -1;

	/* 打印大整数n的值 */
	printf ("n = ");
	mpz_out_str(stdout, 10, n);
	printf ("\n");

	/* 计算(n + 1)的平方 */
	mpz_add_ui(n, n, 1);
	mpz_mul(n, n, n);

	/* 打印(n + 1)平方的值 */
	printf ("(n + 1) ^ 2 = ");
	mpz_out_str(stdout, 10, n);
	printf("\n");

	/* 清除和释放大整数n */
	mpz_clear(n);

	return 0;
}
编译GMP应用代码时,需同时链接数学库,GCC环境下可以这样编译:

gcc gmpcalc.c -lgmp -lm

你可能感兴趣的:(C语言,C语言,大数运算,gmp)