Basicaly when i run the code it works if i give it a large number (splitting it in prime numbers,but when i want to run it for low numbers it doesnt work) The problem i see is that if i give the program number 8 it doesnt print nothing on the screen.(i think its something to do with 2+2+2+2 ) and if i write 50 it shows all the posibilities WITHOUT repeating 1 prime number on a line
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define is_sol 2
#define is_pos 4
#define impos 0
int n, *st;
int prim (int n)
{
if ( n < 2 )
return impos;
else
if ( n != 2 && (n % 2) == 0)
return impos;
else
{ long i;
for(i = 3; i <=sqrt(1.0*n); i +=2)
if ( n % i == 0)
return impos;
}
return is_pos;
}
int test(int h)
{
int i;
if(!h)
return (st[h] < 2 ? impos : prim(st[h]));
if(st[h] <= st[h-1])
return impos;
int p = st[h];
if(!prim(p))
return impos;
int S = 0;
for(i = 0 ; i <= h ; i++)
S += st[i];
if(S == n)
return is_sol;
return (S < n ? is_pos : impos);
}
void print (int h)
{
int i;
for(i = 0 ; i <= h; i++)
printf("%d ", st[i]);
printf("\n");
}
void back(int h)
{
int k;
for(k = 2; k <= n/2; k++)
{
st[h] = k;
int rez = test(h);
if(rez == is_sol)
print(h);
else
{
if(rez == is_pos)
back(h+1);
}
}
}
int main()
{
printf( "Your number: ");
scanf("%d",&n);
st = (int*)malloc(sizeof(int)*(n/2));
back(0);
}
The condition
is responsible. If you want to write a number as the sum of distinct primes, for small numbers, the only ways often include one prime larger than
n/2– e.g. the only way to write 8 as the sum of distinct primes is8 = 3 + 5.If you make it
k <= n-2, it will work.If you want to allow using the same prime several times, as in
8 = 2+2+2+2or8 = 2+3+3, you need to changeto
in
test.And you should keep track of the sum you have so far to avoid the most blatant inefficiencies. (And store a list of primes instead of checking each number every time.)