/* * ammprobgmp.c * * Calculation for a problem from the American Mathematical Monthly. * (C version using the GNU MP library.) * * Warren Weckesser, Dept. of Mathematics, Colgate University * * * Compile with: * gcc ammprobgmp.c -o ammprobgmp -lgmp */ #include #include #define ONE ((unsigned long) 1) int main(int argc, char **argv) { /* Declare the variables that we will use. */ mpz_t n, nlast; mpz_t m, root, rem; mpz_t n1; /* Check that the user gave two arguments to the command. */ if (argc != 3) { printf("use: %s first last\n",argv[0]); return(-1); } /* Initialize the variables. */ mpz_init_set_str(n,argv[1],10); mpz_init_set_str(nlast,argv[2],10); mpz_init(m); mpz_init(root); mpz_init(rem); mpz_init(n1); while (mpz_cmp(n,nlast) <= 0) /* while n <= nlast ... */ { mpz_add_ui(n1,n,ONE); /* n1 = n+1 */ mpz_mul(m,n,n); /* m = n*n */ mpz_add_ui(m,m,ONE); /* m = m + 1 = n^2+1 */ mpz_mul(m,m,n1); /* m = m*n1 = (n^2+1)(n+1) = n^3+n^2+n^1+1 */ mpz_sqrtrem(root,rem,m); /* Find root & rem such that root^2+rem = m */ if (mpz_sgn(rem) == 0) /* if rem == 0 ... */ { /* Print n, m and root */ mpz_out_str(stdout,10,n); printf(" "); mpz_out_str(stdout,10,m); printf(" "); mpz_out_str(stdout,10,root); printf("\n"); } mpz_add_ui(n,n,ONE); /* n = n + 1 */ } return(0); }