Difference Between Highest and Lowest Prime Digits

The program must accept an integer N as the input. The task is to find the highest and the lowest prime digits in the number and print the difference between them. If no prime digits are found, the program should print -1.

Boundary Condition(s):
0 <= N <= 10^18

Input Format:
The first line contains the integer N.

Output Format:
A single line contains the difference between the highest and lowest prime digits or -1 as described.

Example Input/Output 1:
Input:
42715

Output:
4

Explanation:
The prime digits in the number are 2, 7, and 5. The highest prime digit is 7 and the lowest prime digit is 2. Hence the difference is 7-2 = 5.

Example Input/Output 2:
Input:
60849

Output:
-1

Explanation:
There are no prime digits in the number. Hence the output is -1.

N = input().strip()
prime_digits = [digit for digit in N if digit in '2357']
if prime_digits:
    print(int(max(prime_digits)) - int(min(prime_digits)))
else:
    print(-1)
#include<stdio.h>
#include<limits.h>

int main() {
    char N[20];
    scanf("%s", N);
    int max_prime = INT_MIN;
    int min_prime = INT_MAX;
    for(int i = 0; N[i] != ''; i++) {
        if(N[i] == '2' || N[i] == '3' || N[i] == '5' || N[i] == '7') {
            if(N[i] > max_prime) max_prime = N[i];
            if(N[i] < min_prime) min_prime = N[i];
        }
    }
    if(max_prime != INT_MIN) {
        printf("%d", max_prime - min_prime);
    } else {
        printf("-1");
    }
    return 0;
}
#include <iostream>
#include <climits>
#include <string>
using namespace std;

int main() {
    string N;
    cin >> N;
    char max_prime = CHAR_MIN;
    char min_prime = CHAR_MAX;
    for(char digit : N) {
        if(digit == '2' || digit == '3' || digit == '5' || digit == '7') {
            if(digit > max_prime) max_prime = digit;
            if(digit < min_prime) min_prime = digit;
        }
    }
    if(max_prime != CHAR_MIN) {
        cout << max_prime - min_prime;
    } else {
        cout << "-1";
    }
    return 0;
}
import java.util.Scanner;

public class PrimeDigitDifference {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String N = sc.next();
        char max_prime = '0' - 1;
        char min_prime = '9' + 1;
        for(char digit : N.toCharArray()) {
            if(digit == '2' || digit == '3' || digit == '5' || digit == '7') {
                if(digit > max_prime) max_prime = digit;
                if(digit < min_prime) min_prime = digit;
            }
        }
        if(max_prime != '0' - 1) {
            System.out.println(max_prime - min_prime);
        } else {
            System.out.println("-1");
        }
    }
}
Previous Article

Digits That Are Divisors of the Number

Next Article

Determine if the Number is a Factorial Value

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *