当前位置:网站首页>C language practice (4) -- multiplication and division of large numbers
C language practice (4) -- multiplication and division of large numbers
2022-06-12 18:14:00 【Learn about cust】
List of articles
Preface
Use C Language to achieve multiplication of large numbers .
One 、 What is a large number operation ?
Large number operation , seeing the name of a thing one thinks of its function , Is to do a series of operations on large numbers . In mathematics , There is no upper limit on the value , But in the computer , Due to the limitation of word length , The range that a computer can represent is limited , For large numbers , The computer cannot calculate it directly , Need to use the so-called high-precision algorithm , namely Use arrays to store integers , And simulate the method of manual calculation for four operations .
Two 、 Realization thought —— Simulate manual calculation
Premise : We cannot directly store very large operands as integers , Because the data type has the limitation of byte size . So we Use strings to store large numbers , Each element in a string is a single digit of a large number . The number of elements in a string can be unlimited , Therefore, it is very convenient to store large numbers .
1. Multiplication
Multiplication : In hand calculation , We use the vertical method . That is, each bit of an operand ( From junior to senior ) Multiply all bits of another operand , And add up the results . So we can simulate the operation :
First step : Each element in the two strings Convert to integer and store in reverse order ( That is, the single digits are placed in the first element of the array ) In an array of integers ( Hypothetical array a,b);
The second step : Create a product group (sum), The maximum length of the array is the above array a And b The product of length , Note that the array must be initialized to 0!!!
The third step : use a Each element of the array is multiplied by b All elements of the array ( hypothesis a Array index from i=0 Start ,b Array index from j=0 Start ), Store the results in sum【i+j】 in ;
Step four : Contraproduct array (sum) To organize , From low to high , Dot into one
2. division
division : In hand calculation , We also use vertical calculation , That is, take the first of the divisor n Digit number (n Is the number of digits of the divisor ) Divide by the divisor , If the number is greater than the divisor, divide , The remainder and the remaining digits of the dividend are combined , Repeat the above operation ; If the number is less than the divisor , Then expand this number , That is, take the first of the divisor n+1 Digit number , Repeat the above operation .
In short : Use subtraction , But optimize , Before dividend n The number of subtractions between a digit number and a divisor , To multiply by 10 Of m-n Power , To correctly express quotient .(m Is the number of digits of the dividend )
First step : Store the dividend and divisor in a string ;
The second step : Judge the relationship between the divisor and the dividend . If the divisor is small , The direct exporter is 0, The remainder is the dividend ; If dividend Not less than Divisor , Then perform the following operations ;
The third step : Create loop . If the dividend is not less than the divisor , Before the divisor n Digit number (n Is the number of digits of the divisor ) Create a bit string tem, And will tem Compare size with divisor . If tem Greater than the divisor , Then use tem Subtract each bit of the divisor from each bit of the , If the result is negative, you need to borrow , Loop execution , And record the number of subtractions ; If tem Less than the divisor , Then expand tem, Before the divisor n+1 Bit is created as a string tem, then tem Circularly subtract from the divisor ;
Step four : Enlarged tem In circular subtraction , There are two sequential states .1.tem The number of digits is one more than the divisor ;2.tem There are as many digits as divisors Note that the code handling is different in both cases , Please observe carefully !
3、 ... and 、 Code implementation
1. Multiplication function
The code is as follows :
void Multiply(int n1[], int n2[], int sum[], int m, int n)
{
int i = 0, j = 0;
// take n1 Each bit of the is in turn associated with n2 Multiply all bits of
// The results are accumulated and stored in sum in
for (i = 0; i < m; i++)
{
// The maximum length of the product is m+n
for (j = 0; j < n; j++)
{
sum[i + j] += n1[i] * n2[j];
}
}
// Yes sum Every one of us has a meeting 10 Into the 1
for (i = 0; i < m + n; i++)
{
if (sum[i] > 9)
{
sum[i + 1] += sum[i] / 10;
sum[i] %= 10;
}
}
// Record the last non-zero position
int flag = m + n;
while (sum[flag] == 0)
{
flag--;
}
if (flag == 0)
{
printf("0");
}
else
{
// Output results
printf(" Product as :");
for (i = flag; i >= 0; i--)
{
printf("%d", sum[i]);
}
}
}
2. Division function
The code is as follows :
void Divide(char s1[],char s2[])
{
// Get the digits of two numbers
int m = strlen(s1);
int n = strlen(s2);
// Divisor less than divisor
if (m<n||(m==n&&strcmp(s1,s2)==-1))
{
printf(" merchant :0 remainder :%s",s1);
return;
}
// The divisor is greater than the divisor
else
{
int m = strlen(s1);
int n = strlen(s2);
int sum[Max] = {
0};
int count = 0;
char tem[Max] = {
0 };
// The dividend is not less than the divisor
while (((strcmp(s1, s2) != -1) && m == n)||m>n)
{
count = 0;
int i = 0, j = 0;
// From the first non-zero position of the dividend , Will be back n Bits are stored in tem in
for (i=0;i<n;i++)
{
tem[i] = s1[i];
}
// If the same number of digits tem Not less than s2 Just subtract
if (strcmp(tem, s2) != -1)
{
// use tem Go round and subtract the divisor s2
while (strcmp(tem, s2) != -1)
{
for (i = n-1; i >=0; i--)
{
tem[i] = tem[i] - s2[i] + '0';
if (tem[i] < '0')
{
tem[i] += 10;
tem[i - 1] -= 1;
}
// Record how many times you have lost
}
count++;
}
// take s1 Before n The bit assignment is tem
for (i = 0; i < n; i++)
{
s1[i] = tem[i];
}
// Store the reduced times
sum[m - n] += count;
}
// Same digit tem Less than s2, Just expand tem
else
{
//tem Digit ratio s2 More than a
tem[n] = s1[n];
// use tem Go round and subtract the divisor s2
int l1 = strlen(tem);
while (((strcmp(tem, s2) != -1) && l1 == n) || l1 > n)
{
//tem Than s2 More than a
if (l1==n+1)
{
for (i = l1 - 1, j = n - 1; j >= 0; i--, j--)
{
tem[i] = tem[i] - s2[j] + '0';
if (tem[i] < '0')
{
tem[i] += 10;
tem[i - 1] -= 1;
}
// Record how many times you have lost
}
count++;
if (tem[0] == '0')
{
for (i = 1; i < n + 1; i++)
{
tem[i - 1] = tem[i];
}
tem[n] = '\0';
}
}
//tem And s2 Same number of digits
else if(l1==n)
{
for (i = n - 1; i >= 0; i--)
{
tem[i] = tem[i] - s2[i] + '0';
if (tem[i] < '0')
{
tem[i] += 10;
tem[i - 1] -= 1;
}
}
// Record how many times you have lost
count++;
}
l1 = strlen(tem);
}
// take s1 Before n+1 The bit assignment is tem
s1[0] = '0';
for (i = 1; i < n+1; i++)
{
s1[i] = tem[i-1];
}
// Store the reduced times
sum[m - n-1] += count;
}
// Arrangement s1, Remove the... Before the string 0
// Find the first non-zero position
i = 0;
while (s1[i] == '0')
{
i++;
}
// take s1 Move array forward i A unit of
for (j = i; j < m; j++)
{
s1[j - i] = s1[j];
}
// After the array i The first element is assigned to \0
for (j = m - i; j < m; j++)
{
s1[j] = 0;
}
// Record the current s1 Number of digits
m = strlen(s1);
}
//sum It's business ,s1 It's the remainder
printf(" merchant :");
int flag = Max-1;
int i = 0;
while (sum[flag] == 0)
{
flag--;
}
for (i = flag; i >= 0; i--)
{
printf("%d", sum[i]);
}
printf("\n remainder :");
if (s1[0] != 0)
{
printf("%s", s1);
}
else
{
printf("0");
}
}
}
3. The main function
The code is as follows :
int main()
{
char s1[Max], s2[Max];
// Note that when creating a product group , To initialize the array to 0
int n1[Max], n2[Max], sum[Max * Max]={
0};
// Enter two large numbers as strings
printf(" Please enter two large numbers :\n");
while (1)
{
scanf("%s %s", s1, s2);
if (s1[0] != '0' && s2[0] != '0')
break;
else
{
printf(" Large numbers are not allowed 0 start , Please re-enter two large numbers :");
}
}
// Get the length of two strings
int m = strlen(s1);
int n = strlen(s2);
// Convert each bit of the string into an integer and store it in reverse order
int i = 0, j = 0;
for (i = 0; i < m; i++)
{
n1[i] = s1[m - i - 1] - '0';
}
for (j = 0; j < n; j++)
{
n2[j] = s2[n - j - 1] - '0';
}
printf(" Please select :1. Multiplication 2. division \n");
int input = 0;
scanf("%d", &input);
if (input == 1)
{
Multiply(n1, n2, sum, m, n);
}
else if (input == 2)
{
Divide(s1,s2);
}
return 0;
}
Four 、 The actual effect
summary
When implementing large number division , Hybrid implementation of large number subtraction , This makes the code very bloated .
The code can first implement the large number subtraction function , Then we can divide large numbers . This will simplify the division of large numbers , Beautify the look and feel .
边栏推荐
- LCD parameter interpretation and calculation
- Introduction to service grid and istio - continued
- 小程序+App,低成本获客及活跃的一种技术组合思路
- Stack in JS (including leetcode examples) < continuous update ~>
- USB to serial port - maximum peak serial port baud rate vs maximum continuous communication baud rate
- Vant3+ts encapsulates uploader upload image component
- Summary of static memory allocation and dynamic memory allocation
- DRM driven MMAP detailed explanation: (I) preliminary knowledge
- Applet and app are owned at the same time? A technical scheme with both
- HTTP缓存<强缓存与协商缓存>
猜你喜欢
VirtualLab基础实验教程-5.泊松亮斑
JDBC quick start tutorial
Applet and app are owned at the same time? A technical scheme with both
VirtualLab basic experiment tutorial -6 Blazed grating
C operation database added business data value content case school table
An easy-to-use IDE for small programs
High speed layout guidelines incomplete
MYSQL:Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column
小程序和App同时拥有?两者兼得的一种技术方案
Vant3 +ts packaged simple step advancer component
随机推荐
C语言练习(4)——大数乘除
Use applet to quickly generate app in seven steps
干货 | 一文搞定 pytest 自动化测试框架(二)
Section qemu+gdb
Esp32-c3 esp-idf configuring smartconfig and SNTP to obtain network time
有源差分晶振原理图以及LV-PECL、LVDS、HCSL区别
A story on the cloud of the Centennial Olympic Games belonging to Alibaba cloud video cloud
Schedule update | 2022 Microsoft and Intel hacker song competition is in hot registration
MYSQL:Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column
Remote gadget putty (Alibaba cloud mirror station address sharing)
JS sum of two numbers
Still using Microsoft office, 3 fairy software, are you sure you don't want to try?
小程序+App,低成本获客及活跃的一种技术组合思路
High speed layout guidelines incomplete
js二分法
torch.where的新用法(很老但是大家忽略的用法)
Leetcode151 flipping words in strings
leetcode 300. 最长递增子序列
Extreme Programming -- Practice of root cause analysis
Gospel of audio and video developers, rapid integration of AI dubbing capability