計算 1 到 n 之間所有數字中各個數字之和


在本教程中,我們將找到 1 到 n 之間所有數字各數字之和。例如,54 的各數字之和是 5 + 4 = 9,以此類推,我們需要找到所有數字以及其各數字之和。

我們知道,可以生成 10d - 1 個數字,它們的數字位數為 d。若要找到所有位數為 d 的數字之和,我們可以使用遞迴公式。

sum(10d- 1)=sum(10d-1- 1)*10+45*(10d-1)

輸入和輸出

Input:
This algorithm takes the upper limit of the range, say it is 20.
Output:
Sum of digits in all numbers from 1 to n. Here the result is 102

演算法

digitSumInRange(n)

輸入:範圍的上限。

輸出 −指定範圍(1-n)內所有數字的各數字之和。

Begin
   if n < 10, then
      return n(n+1)/2
   digit := number of digits in number
   d := digit – 1
   define place array of size digit
   place[0] := 0
   place[1] := 45

   for i := 2 to d, do
      place[i] := place[i-1]*10 + 45 * ceiling(10^(i-1))
      power := ceiling(10^d)
      msd := n/power
      res := msd*place[d] + (msd*(msd-1)/2)*power +
             msd*(1+n mod power) + digitSumInRange(n mod power)
      return res
   done
End

示例

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

int digitSumInRange(int n) {
   if (n<10)
      return n*(n+1)/2;          //when one digit number find sum with formula
   int digit = log10(n)+1;       //number of digits in number
      int d = digit-1;           //decrease digit count by 1
   
   int *place = new int[d+1];    //create array to store sum upto 1 to 10^place[i]
   place[0] = 0;
   place[1] = 45;

   for (int i=2; i<=d; i++)
      place[i] = place[i-1]*10 + 45*ceil(pow(10,i-1));

   int power = ceil(pow(10, d));    //computing the power of 10
   int msd = n/power;               //find most significant digit
   return msd*place[d] + (msd*(msd-1)/2)*power +
      msd*(1+n%power) + digitSumInRange(n%power);    //recursively find the sum
}

int main() {
   int n;
   cout << "Enter upper limit of the range: ";
   cin >> n;
   cout << "Sum of digits in range (1 to " << n << ") is: " << digitSumInRange(n);
}

輸出

Enter upper limit of the range: 20
Sum of digits in range (1 to 20) is: 102

更新於:16-6-2020

675 次檢視

開啟你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.