This C code performs basic operations on large integers represented...

August 30, 2025 at 10:04 AM

#include <stdio.h> #define LEN 100 void input(int *buffer, int *length); void output(int *buffer, int length); void sum(int *buff1, int len1, int *buff2, int len2, int *result, int *result_length); void sub(int *buff1, int len1, int *buff2, int len2, int *result, int *result_length); int compare(int *buff1, int len1, int *buff2, int len2); int main() { int num1[LEN], num2[LEN]; int len1 = 0, len2 = 0; // Ввод первого числа input(num1, &len1); if (len1 == 0) { printf("n/a"); return 0; } // Ввод второго числа input(num2, &len2); if (len2 == 0) { printf("n/a"); return 0; } int result_sum[LEN + 1], result_sub[LEN]; int len_sum = 0, len_sub = 0; // Сложение sum(num1, len1, num2, len2, result_sum, &len_sum); output(result_sum, len_sum); printf("\n"); // Вычитание (только если num1 >= num2) if (compare(num1, len1, num2, len2) >= 0) { sub(num1, len1, num2, len2, result_sub, &len_sub); output(result_sub, len_sub); } else { printf("n/a"); } return 0; } void input(int *buffer, int *length) { *length = 0; int temp; while (scanf("%d", &temp) == 1) { if (temp < 0 || temp > 9) { *length = 0; return; } if (*length < LEN) { buffer[*length] = temp; (*length)++; } else { *length = 0; return; } char c = getchar(); if (c == '\n' || c == EOF) { break; } } } void output(int *buffer, int length) { if (length == 0) { printf("0"); return; } // Пропускаем ведущие нули int start = 0; while (start < length && buffer[start] == 0) { start++; } if (start == length) { printf("0"); return; } for (int i = start; i < length; i++) { printf("%d", buffer[i]); if (i < length - 1) { printf(" "); } } } void sum(int *buff1, int len1, int *buff2, int len2, int *result, int *result_length) { int carry = 0; int i = len1 - 1, j = len2 - 1, k = LEN; // Заполняем результат нулями for (int idx = 0; idx <= LEN; idx++) { result[idx] = 0; } // Складываем с конца while (i >= 0 || j >= 0 || carry > 0) { int digit1 = (i >= 0) ? buff1[i] : 0; int digit2 = (j >= 0) ? buff2[j] : 0; int total = digit1 + digit2 + carry; result[k] = total % 10; carry = total / 10; i--; j--; k--; } // Определяем длину результата *result_length = 0; for (int idx = k + 1; idx <= LEN; idx++) { result[*result_length] = result[idx]; (*result_length)++; } } void sub(int *buff1, int len1, int *buff2, int len2, int *result, int *result_length) { int borrow = 0; int i = len1 - 1, j = len2 - 1; // Заполняем результат нулями for (int idx = 0; idx < LEN; idx++) { result[idx] = 0; } // Вычитаем с конца while (i >= 0) { int digit1 = buff1[i]; int digit2 = (j >= 0) ? buff2[j] : 0; int diff = digit1 - digit2 - borrow; if (diff < 0) { diff += 10; borrow = 1; } else { borrow = 0; } result[i] = diff; i--; j--; } // Убираем ведущие нули *result_length = len1; int start = 0; while (start < *result_length && result[start] == 0) { start++; } if (start == *result_length) { // Результат равен нулю *result_length = 1; result[0] = 0; } else { // Сдвигаем результат *result_length -= start; for (int idx = 0; idx < *result_length; idx++) { result[idx] = result[start + idx]; } } } int compare(int *buff1, int len1, int *buff2, int len2) { // Убираем ведущие нули для корректного сравнения int start1 = 0, start2 = 0; while (start1 < len1 && buff1[start1] == 0) start1++; while (start2 < len2 && buff2[start2] == 0) start2++; int actual_len1 = len1 - start1; int actual_len2 = len2 - start2; if (actual_len1 > actual_len2) return 1; if (actual_len1 < actual_len2) return -1; for (int i = 0; i < actual_len1; i++) { if (buff1[start1 + i] > buff2[start2 + i]) return 1; if (buff1[start1 + i] < buff2[start2 + i]) return -1; } return 0; }

This C code performs basic operations on large integers represented as arrays of digits. Here's an explanation of its components and what it does:

Overview:

  1. Input:

    • It allows the user to input two non-negative integers digit by digit. The numbers are stored in arrays where each element corresponds to a single digit of the number.
    • Input validation ensures that digits are between 0 and 9. It rejects invalid inputs or overly long integers (greater than 100 digits).
  2. Output:

    • Displays numbers stored in arrays, skipping leading zeros for clean formatting.
  3. Addition (sum function):

    • Adds two large integers stored as arrays. Handles carrying over digits when sums exceed 9.
    • Produces the result in a new array and determines the correct length of the result.
  4. Subtraction (sub function):

    • Subtracts one large number from another (assuming the first number is greater than or equal to the second).
    • Handles borrowing when subtraction generates negative values at any digit position.
    • Result is also stored in an array, with leading zeros stripped appropriately.
  5. Comparison (compare function):

    • Compares two large integers (stored as arrays).
    • Returns:
      • 1 if the first number is greater,
      • -1 if the second number is greater,
      • 0 if they are equal.
  6. Main Program:

    • Reads two integers using the input() function.
    • Performs addition and displays the result.
    • Performs subtraction only if the first number is greater than or equal to the second number; otherwise, it prints "n/a" for subtraction.

Key Features:

  • Uses arrays (int num1[], int num2[]) to handle large integers. Each digit of the number is stored as an array element, making it possible to handle numbers much larger than those supported by native integer types.
  • Enforces limits on the input size (LEN = 100), ensuring no more than 100 digits can be stored.
  • Handles carrying and borrowing in addition and subtraction operations.
  • Skips leading zeros to provide a clean output.

Details of Functions:

  1. input(int *buffer, int *length)

    • Reads digits from the user and stores them in the buffer array.
    • If an invalid character is encountered or the number exceeds the limit (LEN), it resets the length to 0 (indicating a failed input).
  2. output(int *buffer, int length)

    • Outputs the number stored in the buffer, ignoring leading zeros.
    • Outputs 0 if the number is zero or if the length is zero.
  3. sum(int *buff1, int len1, int *buff2, int len2, int *result, int *result_length)

    • Adds two numbers stored in buff1 and buff2. Handles carrying over digits when needed.
    • The result is stored in the result array, and the length of the result is updated in result_length.
  4. sub(int *buff1, int len1, int *buff2, int len2, int *result, int *result_length)

    • Subtracts buff2 from buff1.
    • Handles cases where borrowing is required to perform the subtraction.
    • Supports results with leading zeros, which are stripped before finalizing the result_length.
  5. compare(int *buff1, int len1, int *buff2, int len2)

    • Compares buff1 and buff2 and determines whether the first number is greater than, smaller than, or equal to the second.
    • Skips leading zeros to make valid comparisons.

Example Execution:

Input:

12345
6789

Output:

19134
5556

Explanation of Output:

  • The sum of 12345 and 6789 is 19134.
  • The difference (12345 - 6789) is 5556. Subtraction is performed because 12345 >= 6789.

Error Handling:

  1. If the input contains invalid digits (not between 0 and 9) or exceeds LEN, the program will terminate and output "n/a".
  2. If subtraction is attempted when the first number is less than the second, the program will output "n/a" for the subtraction result.
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node