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.