Robert Locke
Robert Locke

Reputation: 465

Print large integer as exponential function

I would like to print a huge integer in exponential form. Something like

Value 123456789012 as exp is 1.2345*10^12.

Is there any gmp_printf format to handle this or should I calculate it first with some mpz_get_exp function?

mpz_t integer;
mpz_t exponent;
mpf_t top;

mpz_inits(integer, exponent, null);
mpf_init(top);

mpz_set_str(integer, "123456789012", 10);

???

gmp_printf("Value %Zd as exp is %.4Ff*10^%Zd",
           integer, top, exonent);

Upvotes: 1

Views: 512

Answers (2)

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37934

The %Fe or %FE format specifier expects an object of mpf_t type. Hence, you would need to create temporary variable just for gmp_printf(). For instance:

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

int main(void)
{
    mpz_t integer;

    mpz_init_set_str(integer, "123456789012", 10);
    /* Print integer's value in scientific notation */
    {
        mpf_t tmp_float;
        mpf_init(tmp_float);
        mpf_set_z(tmp_float, integer);
        gmp_printf("%.4FE\n", tmp_float);
        mpf_clear(tmp_float);
    }
    mpz_clear(integer);
    return 0;
}

Resulting into:

1.2346E+11

Alernatively you could export it into POD double by mpz_get_d and print it by ordinary printf():

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

int main(void)
{
    mpz_t integer;

    mpz_init_set_str(integer, "123456789012", 10);
    printf("%.4E\n", mpz_get_d(integer));

    mpz_clear(integer);
    return 0;
}

I would preffer second approach is it looks much cleaner.

Upvotes: 1

mattm
mattm

Reputation: 5949

The gmplib documentation seems to indicate that the %e or %E printf options should work just fine. These print in scientific notation.

gmp_printf("%e", integer);

Upvotes: 1

Related Questions