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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值