Product of N with its largest odd digit in C

In C programming, we need to find the product of a given number N with its largest odd digit. If the number contains no odd digits, we return -1.

Syntax

int largestOddDigit(int n);
int findProduct(int n);

Algorithm

  • Extract each digit of the number using modulo operation
  • Check if the digit is odd and compare with the current largest odd digit
  • Keep track of the maximum odd digit found
  • Multiply the original number with the largest odd digit
  • Return -1 if no odd digit exists

Example 1: Number with Odd Digits

Let's find the product of 15637 with its largest odd digit −

#include <stdio.h>

int largestOddDigit(int n) {
    int largest = -1;
    while (n > 0) {
        int digit = n % 10;
        if (digit % 2 == 1 && digit > largest) {
            largest = digit;
        }
        n = n / 10;
    }
    return largest;
}

int findProduct(int n) {
    int largest = largestOddDigit(n);
    if (largest == -1) {
        return -1;
    }
    return n * largest;
}

int main() {
    int n = 15637;
    printf("Number: %d<br>", n);
    printf("Product with largest odd digit: %d<br>", findProduct(n));
    return 0;
}
Number: 15637
Product with largest odd digit: 109459

Example 2: Number with No Odd Digits

Let's test with a number that has only even digits −

#include <stdio.h>

int largestOddDigit(int n) {
    int largest = -1;
    while (n > 0) {
        int digit = n % 10;
        if (digit % 2 == 1 && digit > largest) {
            largest = digit;
        }
        n = n / 10;
    }
    return largest;
}

int findProduct(int n) {
    int largest = largestOddDigit(n);
    if (largest == -1) {
        return -1;
    }
    return n * largest;
}

int main() {
    int n = 246;
    printf("Number: %d<br>", n);
    int result = findProduct(n);
    if (result == -1) {
        printf("No odd digit found, result: %d<br>", result);
    } else {
        printf("Product with largest odd digit: %d<br>", result);
    }
    return 0;
}
Number: 246
No odd digit found, result: -1

How It Works

  • The largestOddDigit() function extracts digits from right to left using n % 10
  • For each digit, it checks if it's odd using digit % 2 == 1
  • It maintains the largest odd digit found so far
  • The findProduct() function multiplies the original number with the largest odd digit

Conclusion

This approach efficiently finds the largest odd digit by traversing through each digit of the number. The time complexity is O(log n) where n is the input number, as we process each digit once.

Updated on: 2026-03-15T12:56:28+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements