C++ C++;将偶数分解为素因子
我创建了一个程序,它可以将给定的偶数分解为两个素数的和C++ C++;将偶数分解为素因子,c++,C++,我创建了一个程序,它可以将给定的偶数分解为两个素数的和 #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
#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;
}
#包括
#包括
使用名称空间std;
整数i(整数x,整数y)
{
如果(x>y)
{
如果(x%y)
返回i(x,y+1);
其他的
返回0;
}
其他的
返回(x>1);
}
int main()
{
INTA,b;
做
{
cout>a;
如果(a%2==0&&a>=1)
{
对于(b=a/2;b>1;b--)
{
如果((i(b,2)和&i(a-b,2))&&
printf(“%i+%i\n”,b,a-b));
}
}
否则如果(a%2!=0&&a>=1)
{
cout检查以下内容:
// 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);
}
}
//打印给定数字n的所有素数因子的函数
空隙系数(int n)
{
//打印除以n的2的数量
而(n%2==0){
printf(“%d”,2);
n=n/2;
}
//n在这一点上必须是奇数,所以我们可以跳过一个元素(注i=i+2)
对于(int i=3;i 2){
printf(“%d”,n);
}
}
从来看,这可能不是解决问题的最佳方法,但你可以去做,也可以有一个有限的目的:-)
intr,q,a,i;
cout>a;
如果(a%2==0&&a>=1)
{
对于(i=2;您提供的代码与您的目标几乎没有任何共同之处。您所要求的是所谓的因子分解,并且会不断地被重新访问。深入研究,并提出更具体的问题。哦,谢谢。此代码似乎与我的期望更相关。感谢您的帮助。此程序确实令人鼓舞。欢迎:-)你可以帮我把它标在给定的记号上作为答案:-P
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";
}