calcbigmulti.cpp

来自「计算大数乘法的算法示例」· C++ 代码 · 共 85 行

CPP
85
字号
// CalcBigMulti.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "memory.h"

int main(int argc, char* argv[])
{
	int result[3000]={0};
	int temp[3000] = {0};
	int temp2[3000] = {0};
	int cnt = 1;

	result[0] = 1;

	int B[4] = {0};    //乘数的每一位
	
	long t1 = GetTickCount();

	for(int i=1; i<=18; i++)
	{
		//挑出i的每一位    
		int tmp = i;
		int icnt = 0;
		while(tmp)
		{
			B[icnt] = tmp%10;  //i的每一位
			tmp /= 10;
			icnt ++;
		}
		
		//result * i
		for(int k=0; k<icnt; k++) //i的每一位
		{
			//用r去乘, temp保存结果
			int ttmp = 0;
			for(int j=0; j<cnt; j++)
			{	
				int tt = B[k] * result[j];
				
				ttmp = tt+temp[j];
				temp[j] = ttmp%10;
				temp[j+1] = ttmp/10;
			}

			cnt ++;
			
			//求和
			for(j=0; j<cnt; j++)
			{
				temp2[j+k] += temp[j];
			}

			//清零
			memset(temp, 0, 3000*sizeof(int));
		}

		//将temp2的结果付给result
        memcpy(result, temp2, sizeof(int)*3000);
		memset(temp2, 0, sizeof(int)*3000);
	}

	long t2 = GetTickCount() - t1;

	bool flag = 0;
	int n = 0;
	for(i = cnt-1; i>=0; i--)
//	for(i=0; i<cnt; i++)
	{
		if(result[i]>0)flag = 1;

		if(flag)
		{
			printf("%d", result[i]);
			n ++;
		}
	}

	printf("\n%d   %ld\n", n, t2);

	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?