I'm just learning programming and my task was to writce a code in C++ that for given even number would return this number as a sum of two primes. Previously I managed to write a code checking if number is prime or not but as I tried to apply this, my program failed.
#include <iostream>
using namespace std;
int main()
{
int a,s1=0,s2=0;
cout<<"Enter any even natural number greater than 3."<<endl;
cin>>a;
for(int i=0;i<a;++i)
{
for(int k=2;k<=i;++k)
{
if(i%k!=0) s1++;
}
for(int t=2;t<=(a-i);++t)
{
if((a-i)%t!=0) s2++;
}
if(s1==i-2 && s2==a-i-2) cout<<a<<"="<<i<<"+"<<a-i<<endl;
}
return 0;
}
Only one small change needed that I can see, you need to set s1 and s2 to zero inside your loop, not just once at the beginning of main
.
for(int i=0;i<a;++i)
{
s1=s2=0;
...
Now (if you feel like it) rewrite the code using a function called is_prime
. This function takes one integer parameter and returns true if the integer is a prime (and false if not). Had you written such a function in the first place then you would not have made the mistake you did.
Breaking complex problems into smaller ones by writing functions is an absolutely vital skill in programming.