The program must accept an integer N as the input. The task is to calculate the average of all the prime digits present in the number and print the result. If no prime digits are found, the program should print -1.
Boundary Condition(s):
1 <= N <= 10^8
Input Format:
The first line contains the number N.
Output Format:
The first line contains the average of the prime digits or -1.
Example Input/Output 1:
Input:
12345
Output:
2
Explanation:
The prime digits in the number are 2, 3, and 5. The average is (2+3+5)/3 = 10/3 = 3.33. Rounded down, the output is 3.
Example Input/Output 2:
Input:
4690
Output:
-1
Explanation:
There are no prime digits in the number.
n = input().strip()
prime_digits = ['2', '3', '5', '7']
total = count = 0
for digit in n:
if digit in prime_digits:
total += int(digit)
count += 1
if count:
print(total // count)
else:
print("-1")
#include<stdio.h>
int main() {
char num[9];
scanf("%s", num);
int total = 0, count = 0;
for(int i = 0; num[i] != ' '; i++) {
if(num[i] == '2' || num[i] == '3' || num[i] == '5' || num[i] == '7') {
total += (num[i] - '0');
count++;
}
}
if(count) {
printf("%d", total/count);
} else {
printf("-1");
}
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string num;
cin >> num;
int total = 0, count = 0;
for(char c : num) {
if(c == '2' || c == '3' || c == '5' || c == '7') {
total += (c - '0');
count++;
}
}
if(count) {
cout << (total/count);
} else {
cout << "-1";
}
return 0;
}
import java.util.Scanner;
public class PrimeDigitAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String num = sc.next();
int total = 0, count = 0;
for(char c : num.toCharArray()) {
if(c == '2' || c == '3' || c == '5' || c == '7') {
total += (c - '0');
count++;
}
}
if(count > 0) {
System.out.println(total/count);
} else {
System.out.println("-1");
}
}
}
Leave a Reply