c lang solution № 2
This commit is contained in:
parent
ad8db5fd79
commit
defed24cd0
1 changed files with 78 additions and 0 deletions
78
c/solution2.c
Normal file
78
c/solution2.c
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h> // atoi, malloc
|
||||||
|
|
||||||
|
void ten_to_bin(int count, long long x, char *mask) {
|
||||||
|
int i = 0;
|
||||||
|
while (i < count) {
|
||||||
|
mask[i] = (x & 1) + '0'; // Побитовое И вместо % 2
|
||||||
|
mask[i+1] = '\0';
|
||||||
|
x >>= 1; // Побитовый сдвиг вправо вместо / 2
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int calculate_sum(int count, int *numbers, char *mask) {
|
||||||
|
int x = 0;
|
||||||
|
for (int i = 0; mask[i] != '\0'; i++) {
|
||||||
|
if (mask[i] == '1') {
|
||||||
|
x += numbers[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
void find_sum(int count, long long target, int *numbers, char *mask) {
|
||||||
|
// Битовый сдвиг вместо pow(2, count)
|
||||||
|
long long total_combinations = (1LL << count);
|
||||||
|
printf("Total combinations: %lld\n", total_combinations);
|
||||||
|
|
||||||
|
for (long long i = 0; i < total_combinations; i++) {
|
||||||
|
ten_to_bin(count, i, mask);
|
||||||
|
long long current_sum = calculate_sum(count, numbers, mask);
|
||||||
|
|
||||||
|
if (current_sum == target) {
|
||||||
|
printf("OK: %s\n", mask);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf("NO: not found.\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// gcc -O3 solution2.c -o solution -lm
|
||||||
|
// ./solution 477550 15800 1525 35300 19410 25000 15800 1525 35300 19410 25000
|
||||||
|
// 15800 1525 35300 19410 25000 15800 1525 35300 19410 25000 15800 1525 35300
|
||||||
|
// 19410 25000
|
||||||
|
int main(int argc, char *argv[]) {
|
||||||
|
// 1. Валидация ввода
|
||||||
|
if (argc < 5) {
|
||||||
|
printf("ER: input parameters \n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (argc > 30) {
|
||||||
|
printf("ER: input parameters \n");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Формирование массива int
|
||||||
|
long long target = atoi(argv[1]); // Требуемая сумма
|
||||||
|
int count = argc - 2; // Количество переданных чисел
|
||||||
|
int *numbers = malloc(count * sizeof(int)); // Создаем массив
|
||||||
|
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
// Преобразуем каждый аргумент (начиная с argv[2]) в int
|
||||||
|
numbers[i] = atoi(argv[i + 2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Формирование массива char
|
||||||
|
// +1 для символа конца строки '\0'
|
||||||
|
char *mask = calloc(count + 1, sizeof(char));
|
||||||
|
|
||||||
|
// 4. Данные готовы, начинаем считать
|
||||||
|
find_sum(count, target, numbers, mask);
|
||||||
|
|
||||||
|
// 5. Освобождаем память
|
||||||
|
free(mask);
|
||||||
|
free(numbers);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue