在C 中有电源数字总和

Having issues in power digit sum in C++

本文关键字:数字 电源      更新时间:2023-10-16

2^15 = 32768,其数字之和为3 2 7 6 6 8 = 26。

数字2^1000的数字之和是多少?

目前,我正在使用C 的电源数字总和。我的程序正常工作,但会提供不适当的输出。

#include<iostream>
#include<math.h>
using namespace std;
long double calculate(long double n)
{
    long double i,j,temp = 0,sum = 0;
    while(n != 0)
    {
        temp = fmod(n,10);
        sum = sum + temp;
        n = n / 10;
    }
    return sum;
}
int main()
{
    long double i,j,n = 1000,temp = 1,value = 0;
    for(i = 1;i <= n;i++)
    {
        temp = temp * 2;
    }
    cout << "Multiplication is : " << temp << endl;
    value = calculate(temp);
    cout.precision(100);
    cout << "Sum is : " << value << endl;
    return 0;
}

我得到了这样的O/P。

Multiplication is : 1.07151e+301
Sum is : 1200.63580205668592182366438692042720504105091094970703125

它不应该在点。它应该以数字打印。

代表二进制中2^1000的

将占1000位。双打只有64 bit的长度(根据编译器/体系结构,长双打是80或128位)。因此,双打大约代表2^1000。calculate的输入不是2^1000,而是与80bits允许的接近近似值。该近似值不包含calculate要概括的最低数字。

您不能使用任何原始数据类型来计算2^1000及以后的数字总和,因为它是一个大数字(但是,在Python和Ruby等语言中,您可以这样做)。

要在C/C 中解决此问题,您必须使用数组(或任何其他线性数据结构(例如链接列表)等),并应用类似于乘法数字的通常的逻辑。

首先尝试在2^1000中找到数字数量的绑定,然后初始化一个大小的整数阵列,其大小大于所有零。将最后一个元素保持在1。现在将数组(将其视为大数字,以使每个数字都在数组的另一个单元格中),用2,000次乘以Modulo并携带。

这是上述逻辑的代码:

int ar[303];
int sum =0;
ar[0]=1;
for(int j=1;j<303;j++)
    ar[j]=0;
for(int i=1;i<1001;i++)
{
    ar[0]=2*ar[0];
    for(int k=1;k<303;k++)
        ar[k]=2*ar[k] + ar[k-1]/10;
    for(int j=0;j<303;j++)
        ar[j]=ar[j]%10;
}
for(int i=0;i<303;i++)
sum = sum + ar[i];
cout<<sum;

希望它有帮助。

用小数点获得总和的原因是因为您将 double 除以10小数点前的最后一位数为零。

示例:376/10 = 37.6

370/10 = 37

在第12行上的代码中求解此更改:n =(n-temp)/10;

这将至少从您的总和中切出浮点数。

最后我解决了我的问题。

#include<iostream>
#include<math.h>
#include<string>
using namespace std;
long double calculate(string n)
{
    long double i,j,temp = 0,sum = 0;
    for (i = 0;i < n.length();i++)
    {
        if(n[i] == '.')
        {
            break;
        }
        sum = sum + (n[i] - 48);
    }
    return sum;
}
int main()
{
    long double i,j,n = 1000,temp = 1,value = 0;
    string str;
    temp = pow(2,n);
    cout << "Power is : " << temp << endl;
    str = to_string(temp);
    cout << str << endl;
    value = calculate(str);
    cout.precision(100);
    cout << "Sum is : " << value << endl;
    return 0;
}