Skip to content

Instantly share code, notes, and snippets.

@asm-jaime
Last active September 20, 2016 20:19
Show Gist options
  • Save asm-jaime/ee82715e958ade5210dd302a3bdb16a3 to your computer and use it in GitHub Desktop.
Save asm-jaime/ee82715e958ade5210dd302a3bdb16a3 to your computer and use it in GitHub Desktop.
place plus/minus signs between the digits (on C)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int current_sum = 0;
/* return pointer on vector with random numbers*/
int* get_rnd1d_vector(const int *count_num, const int *max_num){/*{{{*/
int* vector = malloc((*count_num) * sizeof(int));
for (int i = 0; i < (*count_num); ++i)
{
vector[i] = rand() % (*max_num);
/*global variable the current_summ for a test*/
current_sum = current_sum + vector[i]*((rand() % 2)? 1 : -1);
};
printf("current sum: %d \n", current_sum);
return vector;
}/*}}}*/
/* return sum a vector*/
int get_full_sum(const int * this_vector, const int *count_num){/*{{{*/
int this_sum = 0;
for(int i = 0; i < (*count_num); i++){
this_sum = this_sum + this_vector[i];
};
return this_sum;
} /*}}}*/
int get_sign(int * this_vector, int i, int this_sum){/*{{{*/
if (i){
if(get_sign(this_vector, i - 1, this_sum + this_vector[i - 1])){
printf("+%d",this_vector[i - 1]);
return 1;
}
else if(get_sign(this_vector, i - 1, this_sum - this_vector[i - 1])){
this_vector[i - 1] = -this_vector[i - 1];
printf("%d",this_vector[i - 1]);
return 1;
};
return 0;
};
return current_sum == this_sum;
}/*}}}*/
int main(){
const int count_num = 24;
const int max_num = 50000000;
/* 24*5*10^7 = 1.2*10^9 and 1*10^9 */
const int max_sum = 1000000000;
int * this_vector = get_rnd1d_vector(&count_num, &max_num);
if(abs(current_sum) > max_sum){
printf("\noverflow sum\n");
free(this_vector);
return 0;
};
if(get_sign(this_vector, count_num, 0)){
printf("\ntest current sum: %d \n", get_full_sum(this_vector, &count_num));
} else {
printf("\nNo solution");
};
printf("\nand here\n");
free(this_vector);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment