april_day_2026/c/solution2.c
2026-03-28 18:01:06 +03:00

78 lines
2.3 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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