在 C++ 中找到質數 p 在 n! 中的冪


在這個問題中,我們給出數字 n 和質數 p。我們的任務是找到質數 p 在 n! 中的冪

讓我們舉個例子來理解這個問題,

Input : n = 6, p = 2
Output : 4

解決方案方法

解決方法很簡單,只需找到 n! 的值。然後進行因式分解,並找出分解中質數 p 的冪。

此處,數字可以表示為 5! = 30 中 2 的冪分解 3。

n 階乘的值是

$$n!\:=\:n^*(n-1)^*(n-2)^*(n-3)\dotso{^*}2^*1$$ 

$$n!\:=\:3^*2^*1\:=\:6$$

不妨設 n = 6,p = 2,

n! = 6! = (2*3*4*5*6)

n! = 720

720 的因式分解為 2*2*2*2*3*3*5

6! 因式分解中 2 的冪為 4。

因此輸出為 4。

示例

演示我們解決方案執行情況的程式

#include <iostream>
using namespace std;
int powerOfPrimeNfactorial(int N, int P){
   int primePower = 0;
   int factVal = P;
   while (factVal <= N) {
      primePower += N / factVal;
      factVal = factVal * P;
   }
   return primePower;
}
int main(){
   int N = 6;
   int P = 2;
   cout<<"The power of prime number "<<P<<" in "<<N<<"! is "<<powerOfPrimeNfactorial(N, P) << endl;
   return 0;
}

輸出

The power of prime number 2 in 6! is 4

更新於: 01-Feb-2022

186 次瀏覽

開始您的 職業生涯

完成課程以獲得認證

開始
廣告