Prime number additon to get specific value
May 13, 2015 at 3:59am UTC
x has to be greater than 2 and even.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int p1 = 1, p2 = 1, t1 = 0, t2 = 0, x, c1 = 0, c2 = 0;
bool satisfy = false ;
cout << "Enter x: " ; cin >> x;
do
{
if (t2 == 0)
{
for (int i = x; i >= 2; i--)
{
for (int j = 1; j <= i; j++)
{
if (i%j == 0)
{
if (i/j == i || i/j == 1)
c1++;
else
break ;
}
}
if (c1 == 2)
{
if (i == (x-1))
{
c1 = 0;
}
else
{
p1 = i;
cout << "P1 is " << p1 << endl;
break ;
}
}
else
c1 = 0;
}
}
for (int i = 2; i <= x; i++)
{
for (int j = 1; j <= i; j++)
{
if (i%j == 0)
{
if (i/j == i || i/j == 1)
c2++;
else
break ;
}
}
if (c2 == 2)
{
if (p2 == t2)
{
c2 = 0;
t2 = 0;
}
else
{
p2 = i;
cout << "*New* P2 is " << p2 << endl;
t2 = p2;
break ;
}
}
else
c2 = 0;
}
if ((p1+p2) == x)
{
cout << "P1 and P2 are both prime and sum up to x.\n" ;
satisfy = true ;
}
}
while (satisfy == false );
}
When the second loop gets to five it becomes an infinite output at 5, when the output should simply be the next prime number which is 7. Please help, I'm getting really irritated, been looking for a while. The x is 38. P1 is 31 and should be added with 7 to get 38.
Last edited on May 13, 2015 at 2:22pm UTC
May 13, 2015 at 4:18am UTC
How about:
FOR EACH prime y that is <= x/2
z = x - y
IF z is prime THEN break
Last edited on May 13, 2015 at 4:37am UTC
May 13, 2015 at 4:27am UTC
My i variable in the for loop doesnt increment past 5 for some reason ..... the one for the second for loop.
Last edited on May 13, 2015 at 4:27am UTC
Topic archived. No new replies allowed.