- 论坛徽章:
- 0
|
- #include<stdio.h>
- #define set_stat(x) N_stat[x]=1
- #define clr_stat(x) N_stat[x]='\0'
- #define is_free(x) (N_stat[x]=='\0')
- #define is_prime(x) (N_prime[x])
- char *N_prime;
- char *N_stat;
- int *result;
- int layer;
- int cur;
- int n;
- void get_prime()
- {
- int i, j, maxfact;
- memset( N_prime, 1, 2*n );
- for( i = 2; i < n; i++ )
- {
- if( N_prime[i] == '\0' )
- continue;
- j = i;
- while( ( j += i ) < 2*n )
- N_prime[j] = '\0';
- }
- return;
- }
- void prt_result()
- {
- int i;
- for( i = 1; i <= n; i++ )
- printf( "%d ", result[i] );
- printf( "\n" );
- return;
- }
- int getfirst( int bp )
- {
- int i;
- for( i = bp+1; i <= n; i++ )
- if( is_free(i) )
- break;
- return(i);
- }
- int main( int ac, char **av )
- {
- while(1)
- {
- printf( "n=" );
- scanf( "%d", &n );
- if( n == 0 )
- exit(0);
- if( ( N_stat = (char *) calloc( n+1, sizeof(char) ) ) == (char *) NULL )
- {
- perror("calloc");
- exit(1);
- }
- if( ( result = (int *) calloc( n+1, sizeof(int) ) ) == (int *) NULL )
- {
- perror("calloc");
- exit(1);
- }
- if( ( N_prime = (char *) calloc( 2*n, sizeof(char) ) ) == (char *) NULL )
- {
- perror("calloc");
- exit(1);
- }
- get_prime();
- cur = 1;
- layer = 1;
- while(1)
- {
- if( cur > n )
- {
- if( layer == 2 )
- {
- printf( "seach is over\n" );
- break;
- }
- else
- {
- cur = result[--layer];
- clr_stat(cur);
- cur = getfirst(cur);
- }
- }
- else
- {
- if( layer == 1 || is_prime( cur+result[layer-1] ) )
- {
- result[layer] = cur;
- if( layer == n )
- {
- if( is_prime( result[1]+result[layer] ) )
- prt_result();
- cur = n+1;
- }
- else
- {
- set_stat(cur);
- layer++;
- cur = getfirst(0);
- }
- }
- else
- cur = getfirst(cur);
- }
- }
- free( N_stat );
- free( result );
- free( result );
- free( N_prime );
- }
- return( 0 );
- }
复制代码 其实也不是很复杂。用递归写实很小的。这时用很早以前写的一个程序该的,用的是回溯。注意终止条件,如果不是环,结果将要长的多。 |
|