Search code examples
cgmp

From C to GMP implementation


I would ask you how this code written in c would look in GMP. I tried something to write but the library is hard to understand. I don't know how to write operation: r = r*10 + n%10; in gmp. I would be very grateful for help.

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

long long rev(long long n)
{
    long long r = 0;
    while (n > 0)
    {
        r = r*10 + n%10;
        n = n/10;
    }
    return r;
}

bool palindrome(long long n)
{
    return (rev(n) == n);
}

void reverseAdd(long long n)
{
    long long r=0;
    while (n <= 100000000000000)
    {
        r = rev(n);
        printf("stage: %lld + %lld\n",n,r); 

        n = n + r;

        if (palindrome(n))
        {
            printf("Palindrom: %lld\n",n);
            break;
        }
        else if (n > 100000000000000)
        {
            printf("Not a palindrome\n");
        }
    }
}


int main()
{
    long long l;

    printf("Give the number to analyze:");
    scanf("%lld",&l);
    reverseAdd(l);
    return 0;
}

Solution

  • To print mpz_t variables use gmp_printf. GMP adds types ‘Z’, ‘Q’ and ‘F’ for mpz_t, mpq_t and mpf_t respectively.

    The GMP types are:
    
    F   mpf_t, float conversions
    Q   mpq_t, integer conversions
    M   mp_limb_t, integer conversions
    N   mp_limb_t array, integer conversions
    Z   mpz_t, integer conversions
    

    gmp_printf accepts format strings similar to the standard C printf (see Formatted Output in The GNU C Library Reference Manual).

    Referring to your last question and your posted program, you can use gmp_printf to print l. See the program modified below:

    //....
    
    int main()
    {
       int k;
        mpz_t l;
        mpz_t n;
        mpz_init (n);  /* remember to init mpz variables */
        mpz_init (l);
    
        printf("Number to analysis: ");
        gmp_scanf("%Zd",l);
    
        gmp_printf ("%s the mpz number %Zd\n", "You have entered", l);
    
        do
        {
            mpz_set(n, l);
            analyzeAdd(n);
            mpz_add_ui(l,l,1);
    
         }while(false);
    
        gmp_printf ("%s is equal %Zd\n", "Now the n", n);
    
        return 0;
    }
    

    Output:

    Number to analysis: 123321
    You have entered the mpz number 123321
    Now the n is equal 246642