我创建了一个程序,它可以将给定的偶数分成两个素数的总和。
#include <iostream>
#include <stdio.h>
using namespace std;
int i(int x, int y)
{
if (x > y)
{
if (x % y)
return i(x, y + 1);
else
return 0;
}
else
return (x > 1);
}
int main()
{
int a, b;
do
{
cout << "Please input a positive even number: ";
cin >> a;
if (a % 2 == 0 && a >= 1)
{
for ( b = a/2; b > 1; b--)
{
if ((i(b, 2) && i(a-b, 2)) &&
printf("%i + %i\n", b, a-b));
}
}
else if (a % 2 != 0 && a >= 1)
{
cout << a << "="<< a << endl;
}
else
break;
}
while(a >= 4);
return 0;
}
但是,我想将偶数分解为素因子乘以素因子,例如,12 = 2 * 2 * 3.修改程序的任何提示?谢谢你的帮助
答案 0 :(得分:1)
检查出来:
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n%2 == 0){
printf("%d ", 2);
n = n/2;
}
// n must be odd at this point. So we can skip one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i+2){
// While i divides n, print i and divide n
while (n%i == 0){
printf("%d ", i);
n = n/i;
}
}
// This condition is to handle the case when n is a prime number
// greater than 2
if (n > 2){
printf ("%d ", n);
}
}
来自http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
答案 1 :(得分:0)
这可能不是解决问题的最佳方法,但你可以选择或限制目的: - )
int r,q,a,i;
cout << "Please input a positive even number: ";
cin >> a;
if (a % 2 == 0 && a >= 1)
{
for (i=2;i<=a;i++)
{
r=a%i;
while (r==0)
{
cout<<i<<"*";
q=q/i;
r=q%i;
}
}
else
{
cout<<"Number is not even";
}