C++ 程式查詢數字階乘中的第一個數字


在本文中,我們將討論一個程式,該程式用於查詢給定數字階乘中的第一個數字。

基本的方法是找出這個數字的階乘,然後得到它的第一個數字。但是由於階乘最終可能變得太大,所以我們會進行一些微小的調整。

在每個點上,我們都會檢查是否存在尾隨零,並刪除如果存在的話。由於尾隨零對第一個數字沒有影響,因此我們的結果不會改變。

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
int calc_1digit(int n) {
   long long int fact = 1;
   for (int i = 2; i <= n; i++) {
      fact = fact * i;
      //removing trailing zeroes
      while (fact % 10 == 0)
         fact = fact / 10;
   }
   //finding the first digit
   while (fact >= 10)
   fact = fact / 10;
   return fact;
}
int main() {
   int n = 37;
   cout << "The first digit : " << calc_1digit(n) << endl;
   return 0;
}

輸出

The first digit : 1

更新日期:2019年10月3日

235 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告