C++ 程式中的質因子


質因子是給定數字的因子,同時也是素數。

某個數字的因子是用來相乘以得到給定數字的數字。

質因數分解是一個過程,即遞迴地用數字的質因子對數字進行除法,進而找出該數字的所有質因子。

Example :
N = 120
Prime factors = 2 5 3
Factorization : 2 * 2 * 2 * 3 * 5

關於某個數字的質因子需要記住的幾點

  • 某個數字的一組質因子是唯一的。
  • 分解在許多數學運算中很重要,比如整除、求公分母等。
  • 這是密碼學中的一個重要概念。

一個程式,用於找出某個數字的質因子

示例

 現場示例

#include <iostream>
#include <math.h>
using namespace std;
void printPrimeFactors(int n) {
   while (n%2 == 0){
      cout<<"2\t";
      n = n/2;
   }
   for (int i = 3; i <= sqrt(n); i = i+2){
      while (n%i == 0){
         cout<<i<<"\t";
         n = n/i;
      }
   }
   if (n > 2)
   cout<<n<<"\t";
}
int main() {
   int n = 2632;
   cout<<"Prime factors of "<<n<<" are :\t";
   printPrimeFactors(n);
   return 0;
}

輸出

Prime factors of 2632 are :2   2   2   7   47

更新於: 03-Feb-2020

12K+ 檢視

開啟職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.