大整数减法-C语言
- 提问者网友:温旧梦泪无声
- 2021-05-11 15:39
- 五星知识达人网友:一秋
- 2021-05-11 16:04
#include <stdio.h>
#include <string.h>
#include <math.h>
char a[101], b[101];
char rs[10000];
char* _sub( char* a, char* b, int n )
{
int k = 0;
double t;
for ( int i = 0; i < n; ++i ) {
t = a[i] - b[i] + k;
a[i] = (int)( t - floor( t/10 )*10 );
k = (int)floor( t/10 );
}
return a;
}
void strtonum( char* a )
{
strrev( a );
while( *a ) {
*a = *a - '0';
++a;
}
}
char* numtostr( char* a, int n )
{
int i, t, k;
while( a[n-1] == 0 ) --n;
k = n & 1 ? n/2+1 : n/2;
for ( i = 0; i < k; ++i ) {
t = a[i] + '0';
a[i] = a[n-i-1] + '0';
a[n-i-1] = t;
}
return a;
}
char* sub( char* a, char* b )
{
int n = strlen( a );
strtonum( a );
strtonum( b );
_sub( a, b, n );
return numtostr( a, n );
}
void clear() { while( getchar() != '\n'); }
void input( char* a, char* b )
{
memset( a, 0, 100 );
memset( b, 0, 100 );
gets( a );
gets( b );
}
int main()
{
int n;
scanf( "%d", &n );
clear();
while ( n-- ) {
input( a, b );
sprintf( rs, "%s%s\n", rs, sub( a, b ) );
putchar( '\n' );
}
puts( rs );
}
- 1楼网友:七十二街
- 2021-05-11 16:24
这是个老问题了,解决方法就是,自己模拟计算机的位运算,下面有个代码例子,你看一下吧,摘自百度
输出的时候效率太低,还可以改进 Code: //允许生成1120位(二进制)的中间结果 #ifndef BI_MAXLEN #define BI_MAXLEN 35 #define DEC 10 #define HEX 16 class CBigInt { public: //大数在0x100000000进制下的长度 unsigned m_nLength; //用数组记录大数在0x100000000进制下每一位的值 unsigned long m_ulValue[BI_MAXLEN]; CBigInt(); ~CBigInt(); void Mov(unsigned __int64 A); void Mov(CBigInt& A); CBigInt Add(CBigInt& A); CBigInt Sub(CBigInt& A); CBigInt Mul(CBigInt& A); CBigInt Div(CBigInt& A); CBigInt Mod(CBigInt& A); CBigInt Add(unsigned long A); CBigInt Sub(unsigned long A); CBigInt Mul(unsigned long A); CBigInt Div(unsigned long A); unsigned long Mod(unsigned long A); int Cmp(CBigInt& A); void Get(CString& str, unsigned int system=HEX); void Put(CString& str, unsigned int system=HEX); int Rab(); CBigInt Euc(CBigInt& A); CBigInt RsaTrans(CBigInt& A, CBigInt& B); void GetPrime(int bits); }; #endif #include "stdafx.h" #include "BigInt.h" //小素数表 const static int PrimeTable[550]= { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 高精度算法