我想问你这段用 c 语言编写的代码在 GMP 中会是什么样子。我尝试写一些东西,但图书馆很难理解。我不知道如何在gmp中编写操作:r = r*10 + n%10;
。我将非常感谢您的帮助。
#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;
}
最佳答案
要打印mpz_t
变量,请使用gmp_printf
。 GMP 分别为 mpz_t、mpq_t 和 mpf_t
添加类型 'Z'
、'Q'
和 'F'
。
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
接受与标准 C printf
类似的格式字符串(请参阅《GNU C 库引用手册》中的 Formatted Output)。
引用你的上一个问题和你发布的程序,你可以使用gmp_printf
来打印l
。
请参阅下面修改后的程序:
//....
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;
}
输出:
Number to analysis: 123321
You have entered the mpz number 123321
Now the n is equal 246642
关于c - 从C到GMP实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45043815/