我写了一个程序来显示两个间隔之间的数字并检查是否可以表示为两个素数的总和
这是我的代码
//============================================================================================
// Check whether and display a number between two intervals can be expressed as 2 prime number
//============================================================================================
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
int checkPrime (int);
int main()
{
int n1 , n2 , i , j;
bool flag = false;
cout << "Enter two number to check:" << endl;
cin >> n1 >> n2 ;
for (i = n1 ; i <= n2 ; i++)
{
for (j = 2 ; j <= i/2 ; j++ )
{
if(checkPrime (j) && checkPrime (i-j))
{
cout << "Number " << i << " equal sum of two prime number " << j << " + " << i - j << endl;
flag = true;
}
}
if (flag == false)
{
cout << "Number " << i << " can't epress to sum of two prime number " << endl;
}
}
system ("pause");
return 0;
}
int checkPrime (int n)
{
bool flag = true;
for (int i = 2; i <= n/2; i++)
{
if (n % i == 0)
{
flag = false;
break;
}
}
return flag;
}
出局
输入两个数字进行检查:
1
12
Number 1 can't epress to sum of two prime number
Number 2 can't epress to sum of two prime number
Number 3 can't epress to sum of two prime number
Number 4 equal sum of two prime number 2 + 2
Number 5 equal sum of two prime number 2 + 3
Number 6 equal sum of two prime number 3 + 3
Number 7 equal sum of two prime number 2 + 5
Number 8 equal sum of two prime number 3 + 5
Number 9 equal sum of two prime number 2 + 7
Number 10 equal sum of two prime number 3 + 7
Number 10 equal sum of two prime number 5 + 5
Number 12 equal sum of two prime number 5 + 7
缺少11号:-s而我不知道为什么:(请帮我修理它
答案 0 :(得分:1)
您必须在每个循环中重置您的标记,否则一旦设置true
值,就永远不会达到if (flag == false)
。
for (i = n1 ; i <= n2 ; i++)
{
flag = false; /* Reset the flag */
for (j = 2 ; j <= i/2 ; j++ )
{
if(checkPrime (j) && checkPrime (i-j))
{
cout << "Number " << i << " equal sum of two prime number " << j << " + " << i - j << endl;
flag = true;
}
}
if (flag == false)
{
cout << "Number " << i << " can't epress to sum of two prime number " << endl;
}
}