C++ 中階乘的位數統計
給定一個整數,任務是首先計算該數的階乘,然後計算結果中的總位數。
什麼是階乘數
一個數的階乘是透過將該數的數字相乘,同時將數字的值遞減 1 來計算的。它用符號“!”表示,例如 0!、1!、2!、3!、5!,等等。0!和 1!的階乘始終為 1。
I.e. factorial of 2 = 2 * (2-1) = 2 * 1 = 2 factorial of 3 = 3 * (3-1) * (2-1) = 3 * 2 * 1 = 6
例如
Input − factorial(6) Output − number of digits in factorial(6) is: 3
說明 - 由於 6 的階乘值為 720,它包含 3 位數字,因此結果為 3
Input − factorial(12) Output− number of digits in factorial(12) is: 9
說明 - 由於 12 的階乘值為 479001600,它包含 9 位數字,因此結果為 9。
下面程式中使用的解決方法如下
輸入需要計算階乘的數字。
如果數字小於 0,則返回 0,因為負數沒有階乘值。
如果數字為 1,則返回 1,因為 1!為 1 且它有 1 位數字。
如果數字大於 1,即從 2 或更大開始,則建立一個迴圈,從 2 開始,直到它小於或等於數字。
取一個臨時變數,比如 d,在迴圈外將其初始化為 0,並在迴圈內不斷地將其加上 log10(i) 的值,直到 i 的每次迭代。
之後,返回“floor(d)+1”的向下取整值。
列印結果。
示例
#include <iostream>
#include <cmath>
using namespace std;
// This function returns the number of digits present in num!
int count_digits(int num){
// factorial exists only if num <= 0
if (num < 0){
return 0;
}
// base case
if (num <= 1){
return 1;
}
// else iterate through num and calculate the
// value
double d = 0;
for (int i=2; i<=num; i++){
d += log10(i);
}
return floor(d) + 1;
}
int main(){
cout<<"number of digits in factorial(1) is: "<<count_digits(1)<< endl;
cout<<"number of digits in factorial(6) is: "<<count_digits(6) << endl;
cout<<"number of digits in factorial(106) is: "<<count_digits(106) << endl;
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出:
number of digits in factorial(1) is: 1 number of digits in factorial(6) is: 3 number of digits in factorial(106) is: 171
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP