Absolute difference between the first X and last X Digits of N?

Here we will see how to get the absolute difference between the first X and last X digits of a number N. To solve this problem, we first extract the last X digits using the modulus operator, then extract the first X digits by reducing the number's length. Finally, we calculate the absolute difference between these two values.

Syntax

int diffFirstLastDigits(int n, int x);

Algorithm

diffFirstLastDigits(N, X)
begin
    p := 10^X
    last := N mod p
    len := length of the number N
    while len is not same as X, do
        N := N / 10
        len := len - 1
    done
    first := N
    return |first - last|
end

Example

Let's implement this algorithm to find the absolute difference between first and last X digits −

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int lengthCount(int n) {
    return floor(log10(n) + 1);
}

int diffFirstLastDigits(int n, int x) {
    int first, last, p, len;
    
    /* Calculate 10^x to extract last x digits */
    p = pow(10, x);
    last = n % p;
    
    /* Get length of the number */
    len = lengthCount(n);
    
    /* Remove digits from right until we have only x digits */
    while (len != x) {
        n /= 10;
        len--;
    }
    first = n;
    
    /* Return absolute difference */
    return abs(first - last);
}

int main() {
    int n = 568424;
    int x = 2;
    
    printf("Number: %d<br>", n);
    printf("First %d digits: %d<br>", x, n / (int)pow(10, lengthCount(n) - x));
    printf("Last %d digits: %d<br>", x, n % (int)pow(10, x));
    printf("Absolute difference: %d<br>", diffFirstLastDigits(n, x));
    
    return 0;
}
Number: 568424
First 2 digits: 56
Last 2 digits: 24
Absolute difference: 32

How It Works

  1. Extract last X digits: Use n % pow(10, x) to get the remainder when divided by 10^X
  2. Extract first X digits: Keep dividing by 10 until the number length equals X
  3. Calculate difference: Use abs() function to get the absolute difference

Conclusion

This algorithm efficiently extracts the first and last X digits from a number and calculates their absolute difference. The time complexity is O(log n) where n is the input number, making it suitable for large numbers.

Updated on: 2026-03-15T10:57:42+05:30

525 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements