Find the highest occurring digit in prime numbers in a range | C ++ program to find the highest occurring digit in prime numbers in a range L to R . ; Sieve of Eratosthenes ; Returns maximum occurring digits in primes from l to r . ; Finding the prime number up to R . ; Initialise frequency of all digit to 0. ; For all number between L to R , check if prime or not . If prime , incrementing the frequency of digits present in the prime number . ; int p = i ; If i is prime ; Finding digit with highest frequency . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sieve ( bool prime [ ] , int n ) { prime [ 0 ] = prime [ 1 ] = true ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == false ) for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = true ; } } int maxDigitInPrimes ( int L , int R ) { bool prime [ R + 1 ] ; memset ( prime , 0 , sizeof ( prime ) ) ; sieve ( prime , R ) ; int freq [ 10 ] = { 0 } ; int val ; for ( int i = L ; i <= R ; i ++ ) { if ( ! prime [ i ] ) { while ( p ) { freq [ p % 10 ] ++ ; p /= 10 ; } } } int max = freq [ 0 ] , ans = 0 ; for ( int j = 1 ; j < 10 ; j ++ ) { if ( max <= freq [ j ] ) { max = freq [ j ] ; ans = j ; } } return ( max != 0 ) ? ans : -1 ; } int main ( ) { int L = 1 , R = 20 ; cout << maxDigitInPrimes ( L , R ) << endl ; return 0 ; }