用c++编程序:输入一个正整数n,将n分解成质因数乘积的形式
首先,我们可以使用基本编程技巧来解决该问题。为了找出n的质因数分解,我们可以逐步尝试将n除以它的潜在质因数,直到余数为0。当剩余的乘积等于1时,表明n已经分解为它所有可能的质因数乘积。C ++代码如下:
//include libraries.
#include <iostream>
#include <math.h>
using namespace std;
//function to find prime factors of a number n.
void primeFactors(int n) {
cout << "The prime factor(s) of " << n << " is/are :"; //print the input number first.
int count = 0; //to keep track of the factors printed in a line.
// Print the number of 2s that divide n //iterate from 2 to sqrt(n). Note: we only need to check up to sqrt(n) since any factor larger than that will have its corresponding factor less than sqrt(n). for (int i=2; i<=sqrt(n); i++){
while (n%i == 0){ //if i divides evenly, then it is a factor of n cout<<i<<" " ; count++; if (count % 10 == 0) { cout << endl; } n = n/i; } } if (count % 10 != 0 && count > 0){ cout << endl ; } if (count == 0){ cout<<"There are no prime factors."<<endl ; } } int main() { int num; //prompt user for input cout<<"Enter any integer:" ; cin>>num ; primeFactors(num); return 0; }
AI智能问答网
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用创作工场,更聪明、更完整、更原创!