How to check if the sum of two halves of a number is equal in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int sumDigits(long long n) {
    int sum = 0;

    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }

    return sum;
}

int checkHalvesSumEqual(long long n) {
    char s[32];
    sprintf(s, "%lld", llabs(n));

    int length = strlen(s);

    if (length % 2 != 0) {
        printf("The number of digits is NOT even. It cannot be split into two halves: ");
        return 0;
    }

    int half_length = length / 2;

    char first_half[32], second_half[32];

    strncpy(first_half, s, half_length);
    first_half[half_length] = '\0';

    strncpy(second_half, s + length - half_length, half_length);
    second_half[half_length] = '\0';

    long long first_num = atoll(first_half);
    long long second_num = atoll(second_half);

    return sumDigits(first_num) == sumDigits(second_num);
}

int main() {
    long long num1 = 123456;
    long long num2 = 123321;
    long long num3 = 123123;
    long long num4 = 123411;
    long long num5 = 1234321;
    long long num6 = 12321;

    printf("%lld: %s\n", num1, checkHalvesSumEqual(num1) ? "true" : "false");
    printf("%lld: %s\n", num2, checkHalvesSumEqual(num2) ? "true" : "false");
    printf("%lld: %s\n", num3, checkHalvesSumEqual(num3) ? "true" : "false");
    printf("%lld: %s\n", num4, checkHalvesSumEqual(num4) ? "true" : "false");
    printf("%lld: %s\n", num5, checkHalvesSumEqual(num5) ? "true" : "false");
    printf("%lld: %s\n", num6, checkHalvesSumEqual(num6) ? "true" : "false");

    return 0;
}



/*
run:

123456: false
123321: true
123123: true
123411: true
The number of digits is NOT even. It cannot be split into two halves: 1234321: false
The number of digits is NOT even. It cannot be split into two halves: 12321: false

*/

 



answered Dec 22, 2025 by avibootz
edited Dec 22, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int halves_sum_equal(long long n) {
    char s[32];
    sprintf(s, "%lld", llabs(n));

    int len = strlen(s);
    if (len % 2 != 0)
        return 0;   // odd number of digits → cannot split evenly

    int half = len / 2;
    int left_sum = 0, right_sum = 0;

    for (int i = 0; i < half; i++)
        left_sum += s[i] - '0';

    for (int i = half; i < len; i++)
        right_sum += s[i] - '0';

    return left_sum == right_sum;
}

int main(void) {
    long long nums[] = {123456, 123321, 123123, 123411, 1234321, 12321};
    int count = sizeof(nums) / sizeof(nums[0]);

    for (int i = 0; i < count; i++) {
        printf("%lld: %s\n",
               nums[i],
               halves_sum_equal(nums[i]) ? "true" : "false");
    }

    return 0;
}



/*
run:

123456: false
123321: true
123123: true
123411: true
1234321: false
12321: false

*/

 



answered Dec 23, 2025 by avibootz
...