编写一个 C++ 程序,通过示例查找数字的质因数。在此质因数示例中,我们使用了嵌套的 while 循环。
#include<iostream>
using namespace std;
int main()
{
int number, i = 1, j, count;
cout << "\nPlease Enter the Number to find the Prime Factors = ";
cin >> number;
while (i <= number)
{
count = 0;
if(number % i == 0)
{
j = 1;
while(j <= i)
{
if(i % j == 0)
{
count++;
}
j++;
}
if(count == 2)
{
cout << i << " is a Prime Factor\n";
}
}
i++;
}
return 0;
}

下面显示的程序将使用 For 循环查找数字的质因数。
#include<iostream>
using namespace std;
int main()
{
int number, i, j, count;
cout << "\nPlease Enter the Number to find the Prime Factors = ";
cin >> number;
for(i = 1; i <= number; i++)
{
count = 0;
if(number % i == 0)
{
for(j = 1; j <= i; j++)
{
if(i % j == 0)
{
count++;
}
}
if(count == 2)
{
cout << i << " is a Prime Factor\n";
}
}
}
return 0;
}
Please Enter the Number to find the Prime Factors = 72
2 is a Prime Factor
3 is a Prime Factor
这是另一个 示例,用于查找给定数字的质因数。
#include<iostream>
using namespace std;
int main()
{
int number, i, j, isPrime, x;
cout << "\nPlease Enter the Number to find the Prime Factors = ";
cin >> number;
for (i = 2; i <= number; i++)
{
if(number % i == 0)
{
isPrime = 1;
for (j = 2; j <= i/2; j++)
{
x = i % j;
if(i % j == 0)
{
isPrime = 0;
break;
}
}
if(isPrime == 1)
{
cout << i << " is a Prime Factor\n";
}
}
}
return 0;
}
Please Enter the Number to find the Prime Factors = 120
2 is a Prime Factor
3 is a Prime Factor
5 is a Prime Factor
C++ 程序使用递归查找数字的质因数
在此示例中,void findFactors(int number) 方法查找给定数字的因数。而 void findPrime(int number) 方法查找质数。
#include<iostream>
using namespace std;
void findPrime(int number)
{
int i, count = 0;
for (i = 2; i <= number/2; i++)
{
if(number % i == 0)
{
count++;
}
}
if(count == 0 && number != 1 )
{
cout << number << " is a Prime Factor\n";
}
}
void findFactors(int number)
{
for (int i = 1; i <= number; i++)
{
if(number % i == 0)
{
findPrime(i);
}
}
}
int main()
{
int number;
cout << "\nPlease Enter the Number to find the Prime Factors = ";
cin >> number;
cout << "\nThe Prime Factors of a Given Number " << number << " are\n";
findFactors(number);
return 0;
}
Please Enter the Number to find the Prime Factors = 266
The Prime Factors of a Given Number 266 are
2 is a Prime Factor
7 is a Prime Factor
19 is a Prime Factor