File size: 1,742 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "gmp-0000", "name": "GMP arbitrary precision in C and C++"}
{"type": "message", "message": {"role": "system", "content": "You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies."}}
{"type": "message", "message": {"role": "user", "content": "How do I use GMP for arbitrary-precision integers, rationals and floats in C (mpz_t/mpq_t/mpf_t) and C++ (mpz_class)? Show init, set, add/mul, print, and linking. Include code examples."}}
{"type": "message", "message": {"role": "assistant", "content": "**GMP types:** `mpz_t` integers, `mpq_t` rationals, `mpf_t` floats (gmplib.org manual 6.3.0). No practical precision limit besides memory.\n\n```c\n#include <gmp.h>\n\nint main(void) {\n    mpz_t a, d, e;   // integers\n    mpz_init(a);\n    mpz_init_set_str(d, \"133742\", 10);  // init + set from string\n    mpz_init(e);\n    mpz_set_ui(a, 1337);\n    mpz_add(e, a, d);        // e = a + d\n    gmp_printf(\"e = %Zd\\n\", e);\n    mpz_mul(a, e, d);        // a = e * d\n    mpz_clear(a); mpz_clear(d); mpz_clear(e);\n    return 0;\n}\n```\nCompile: `gcc prog.c -lgmp`\n\n```cpp\n#include <gmpxx.h>\n#include <iostream>\nint main() {\n    mpz_class d(\"133742\"), e;  // self-initializing\n    e = 1337 + d;\n    std::cout << e << \"\\n\";\n    return 0;\n}\n```\nCompile: `g++ prog.cc -lgmpxx -lgmp`. Always `mpz_clear` C objects; canonicalize `mpq_t` with `mpq_canonicalize`."}}