prime C语言

#include<stdio.h>
#include<math.h>
#include<stdbool.h>
//exclude N
#define E 0
//include N
#define Id    1

int countPrime;
int *primes;
int *addends;
int N;
int S;

/**
*    Determine whether it is prime
*    @param prime
*/
bool isPrime(int prime){
    int k = (int)sqrt((double)prime);
    for(int i = 2; i <= k; i++){
        if(prime % i == 0)
            return false;
    }
    return true;
}

/**
* Initial Prime 
* @param N Number of addends
* @param S sum
* @param coutPrime_ Number of Primes 
*/
int *getPrime(int *N, int *S, int *coutPrime_){
    
    //Initial Prime
    int P;
    printf("please input N,prime P, S:\n");
    scanf("%d,%d,%d" , N, &P, S);
    
    int *primes_ = malloc(sizeof(int) * (*S - P)); 
    int countPrime = 0;
    for(int i = 0; i < *S - P; i++){
        int digit = *S - P - i;
        if(isPrime(digit) && digit > P)
            primes_[countPrime++] = digit;        
    }
    *coutPrime_ = countPrime; 
    if(countPrime == 0){
        free(primes_);
        return NULL;
    }
    int *primes = malloc(sizeof(int) * countPrime);
    printf("The follows is prime:\n");
    for(int i = 0; i < countPrime; i++){
        primes[i] = primes_[i];
        printf("%5d",primes[i]);
    }
    printf("\n");
    free(primes_);
    return primes;
}
/**
*    Prime numbers after prime P with sum S
*    @param
*/
void printAddends(){
    for(int i = 0; i < countPrime; i++){
        if(addends[i] == Id)
            printf("%5d", primes[i]);
    }
    printf("\n");

/**
*    summed of all addends
*    @param  
*/
bool sumPrimes(){
    int sum = 0;
    int count = 0;
    for(int i = 0; i < countPrime; i++){
        if(addends[i] == Id){
            sum += primes[i];
            count++;
        }
    }
    if(count == N && sum == S)
        return true;
    return false;
}
/**
*    Prime numbers after prime P with sum S
*    @param index 
*/
void primeSum(int index){
    
    if(index == countPrime){
        if(sumPrimes())
            printAddends();
        return ;
    }
    
    addends[index] = E;
    primeSum(index + 1);
    
    addends[index] = Id;
    primeSum(index + 1);
    
}
int main(){
    primes = getPrime(&N, &S, &countPrime);
    addends = calloc(countPrime, sizeof(int));
//    addends = malloc(countPrime * sizeof(int));
    printf("The follows is summarize:\n");
    primeSum(0);
    free(primes);
    free(addends);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/s15948703868/article/details/107659773