大量求和 [英] Summing Large Numbers
问题描述
我在欧拉计划网站上遇到了一些问题,遇到了问题。问题问:算出以下一百五十位数的总和的前十位数。我猜想有某种数学方法可以解决这个问题,但我只是想知道这么大的数字是如何相加的?我将数字存储为字符串,并将每个数字转换为长整数,但是数字太大,以至于总和不起作用。
I have being doing some problems on the Project Euler website and have come across a problem. The Question asks,"Work out the first ten digits of the sum of the following one-hundred 50-digit numbers." I am guessing there is some mathematical way to solve this but I was just wondering how numbers this big are summed? I store the number as a string and convert each digit to a long but the number is so large that the sum does not work.
有没有一种方法可以保存很大的数字数字作为变量(不是字符串)?我不需要代码解决问题,因为我想自己解决问题。
Is there a way to hold very large numbers as a variable (that is not a string)? I do not want the code to the problem as I want to solve that for myself.
推荐答案
我只是想知道这么大的数字是如何相加的?
I was just wondering how numbers this big are summed?
您可以使用数组:
long LargeNumber[5] = { < first_10_digits>, < next_10_digits>....< last_10_digits> };
现在您可以计算2个大数的总和:
Now you can calculate the sum of 2 large numbers:
long tempSum = 0;
int carry = 0;
long sum[5] = {0,0,0,0,0};
for(int i = 4; i >= 0; i--)
{
tempSum = largeNum1[i] + largeNum2[i] + carry; //sum of 10 digits
if( i == 0)
sum[i] = tempSum; //No carry in case of most significant digit
else
sum[i] = tempSum % 1000000000; //Extra digits to be 'carried over'
carry = tempSum/1000000000;
}
for( int i = 0; i < 5; i++ )
cout<<setw(10)<<setfill('0')<<sum[i]<<"\n"; //Pad with '0' on the left if needed
一种将非常大的数字作为变量保存的方法(不是
字符串)?
Is there a way to hold very large numbers as a variable (that is not a string)?
对此没有原始方法,您可以使用任何数据结构(数组/队列/链表)并适当地处理它
There's no primitive for this, you can use any data structure (arrays/queues/linkedlist) and handle it suitably
我想有一些数学方法可以解决这
I am guessing there is some mathematical way to solve this
当然!但是,
我不想让代码出现问题,因为我想自己解决这个问题。
I do not want the code to the problem as I want to solve that for myself.
这篇关于大量求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!