最小公倍數在這種情況下,可以將大量有數以百計的數字。你需要處理這樣的大整數。
gmplib
library(-lgmp
)支持任意精度整數運算:
int have_read_first_number = 0;
mpz_t result, arg;
mpz_inits(result, arg, NULL);
mpz_set_ui(arg, 1u);
/* read decimal integers from stdin: one per line */
while((len = getline(&token, &capacity, stdin)) > 0) {
if (!have_read_first_number) { /* read the first integer */
parse_mpz(token, result);
have_read_first_number = 1; /* successfully read first integer */
}
else { /* read the rest of the numbers */
parse_mpz(token, arg);
}
/* lcm(a, b, c, d) = lcm(lcm(lcm(a, b), c), d) */
mpz_lcm(result, result, arg);
}
if (!have_read_first_number) /* error */
panic("no numbers read");
/* print result as decimal */
mpz_out_str(stdout, 10, result);
puts("");
實施例:
$ gcc lcm.c -o lcm -lgmp && { seq 1 100 | ./lcm; }
69720375229712477164533808935312303556800
Complete program: lcm.c
來源
2013-12-15 08:15:25
jfs