簡體   English   中英

因子數和(不含BigInt)C ++

[英]Factorial digit sum (without BigInt) C++

我想弄清楚如何解決這個問題(Project Euler):

N! 表示n×(n-1)×...×3×2×1

例如,10! = 10×9×...×3×2×1 = 3628800,數字10的數字之和! 是3 + 6 + 2 + 8 + 8 + 0 + 0 = 27。

找到數字100中的數字總和!

使用BigInt不是一個選項,我試圖弄清楚如何僅使用c ++實現解決方案。

我想可能將大數字分成大約7位長的數組或類似的東西然后處理它們但我仍然無法弄清楚如何做到這一點..

提前致謝!

嘗試這個

#include "iostream"
#include "vector"

int n,remainder,sum;
int main ()
{   
    std::vector <int> digits(5000);    
    std::cin>>n;    
    digits[0]=1;
    digits[1]=1;
    for (int k=2;k<n+1;k++) {
        for (int i=1;i<=digits[0];i++) {
            digits[i]=digits[i]*k+remainder;
            remainder=0;
            if (digits[i]>9) {
                remainder=digits[i]/10;
                digits[i]%=10;
                if (i==digits[0])
                digits[0]++;
            }
        }
    }   
    for (int i=digits[0];i>=1;i--)
        sum+=digits[i];
    std::cout<<sum;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM