tinycodinglm / math /gmp-0000.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
1.74 kB
opencode trace
System 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 c...

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.

User

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.

Assistant

GMP types: mpz_t integers, mpq_t rationals, mpf_t floats (gmplib.org manual 6.3.0). No practical precision limit besides memory.

c
#include <gmp.h>

int main(void) {
    mpz_t a, d, e;   // integers
    mpz_init(a);
    mpz_init_set_str(d, "133742", 10);  // init + set from string
    mpz_init(e);
    mpz_set_ui(a, 1337);
    mpz_add(e, a, d);        // e = a + d
    gmp_printf("e = %Zd\n", e);
    mpz_mul(a, e, d);        // a = e * d
    mpz_clear(a); mpz_clear(d); mpz_clear(e);
    return 0;
}

Compile: gcc prog.c -lgmp

cpp
#include <gmpxx.h>
#include <iostream>
int main() {
    mpz_class d("133742"), e;  // self-initializing
    e = 1337 + d;
    std::cout << e << "\n";
    return 0;
}

Compile: g++ prog.cc -lgmpxx -lgmp. Always mpz_clear C objects; canonicalize mpq_t with mpq_canonicalize.