【问题标题】:Sum of digits of N to the power PN 的 P 次方位数之和
【发布时间】:2021-09-26 08:16:39
【问题描述】:

我的 C++ 代码应该将一个数字和一个指数作为整数输入,计算“数字”的“指数”的幂,并将结果的数字相加并输出。它适用于像 10 或 20 这样的小指数值,但对于像 ~ >500 这样的大值给出错误的答案。为了便于计算,我将我的“数字”输入限制为

#include<iostream>
using namespace std;
#include <cmath>


int main(){

  int number, exponent;
  cin >> number >> exponent;
  double product = 1;

  int sum = 0;

  // Write your code here
  for (int i = 0; i < exponent; i++){ 
    product = product * number;
  }
  cout << "THE MAIN PRODUCT IS: " << product << "\n\n";

  while (product > 1){
    sum = sum + fmod(product, 10.0);  // kEEP ADDING THE DIGITS TO THE SUM
    cout << "sum is " << sum << endl;
    product = product / 10.000;
    cout << "product is " << product << endl;
  }

  cout << endl;
  cout << sum << endl;
}

【问题讨论】:

  • 仅供参考 2^1000 是一个很大的数字
  • 你明白什么是整数溢出吗?
  • @KarlKnechtel 不,你能给我解释一下吗?
  • 我认为斜体关键字“整数溢出”是作为搜索词提供给您的,以便您可以进行自己的调查。这是基本的东西。
  • 因为你只需要知道多少位数.. 我认为log equation 应该这样做。这是你要找的吗?

标签: c++ algorithm math integer-arithmetic


【解决方案1】:

指数较大的问题是最终答案的长度或最终答案中的位数。

在 C++ 中,可以表示的最大整数是 18-19 位。

如果数量超过限制,会导致整数溢出。

所以,解决这个问题的最好方法是使用字符串或整数数组。

看看下面的实现:

#include <iostream>
#include <math.h>

// Maximum number of digits in
// output
#define MAX 100000


int multiply(int x, int res[], int res_size) {

    // Initialize carry
    int carry = 0;

    // One by one multiply n with
    // individual digits of res[]
    for (int i = 0; i < res_size; i++) {
        int prod = res[i] * x + carry;

        // Store last digit of
        // 'prod' in res[]
        res[i] = prod % 10;

        // Put rest in carry
        carry = prod / 10;
}

    // Put carry in res and
    // increase result size
    while (carry) {
        res[res_size] = carry % 10;
        carry = carry / 10;
        res_size++;
    }

    return res_size;
}

// This function finds
// power of a number x
long long power(int x, int n)
{

    //printing value "1" for power = 0
    if(n == 0 ){
        return 1;
    }


    int res[MAX];
    int res_size = 0;
    int temp = x;

    // Initialize result
    // Representing base in reverse form
    while (temp != 0) {
        res[res_size++] = temp % 10;
        temp = temp / 10;
    }

    // Multiply x n times
    // (x^n = x*x*x....n times)
    for (int i = 2; i <= n; i++)
        res_size = multiply(x, res, res_size);


    long long final_answer = 0;
    
    //Finally taking sum of all the digits in the answer.
    for(int i=0;i<res_size; i++){
        
        final_answer += res[i];    
    }    
    
    return final_answer;
}


int main() {
    int exponent = 8;
    int base = 34;
    std::cout<<power(base, exponent);
    return 0;
}

输出:

76

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 1970-01-01
    • 2015-02-23
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多