HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Find the highest occurring digit in the prime numbers present between L and R (both inclusive)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
findthepresentinclusivenumbersoccurringbothbetweenhighestand

Problem

Given two numbers L and R, find the highest occurring digit in the
prime numbers present between L and R (both inclusive). If multiple
digits have the same highest frequency print the largest of them. If
there are no prime no.s between L and R, print -1.

How can I optimize this code further in terms of running time?

package com;

import java.util.Arrays;

/**
 * Created by ankur on 19/7/15.
 */
public class HighestOccuringDigit {
    private static int MAX = 1000000;
    private static boolean[] isPrime = generatePrime();
    public static void main(String...strings){

        int index = getMaxOccuredDigit(13,13);
        if (index != 0){
            System.out.println(index);
        }else{
            System.out.println(-1);
        }
    }

    private static int getMaxOccuredDigit(int lower, int higher){
    int[] highestDigitCount = new int[10];
    int max = 0;
    int maxIndex = 0;
    if (lower > 1;
        //System.out.println(i);
        if (((i & 1) != 0)   && isPrime[index]){
            //System.out.println(i);
            int[] digitsCount = getDigitCount(i);
            for (int j = 0; j  max){
                    max = highestDigitCount[j];
                }
            }
        }
    }
    if (max == 0){
        return 0;
    }
    for(int i = 0; i > 1) - 1;
        int limit = (int) ((MAX - 1) >> 1);
        boolean[] isPrime = new boolean[limit];
        Arrays.fill(isPrime, true);
        for( int i = 0; i< root; i++){
            if(isPrime[i]){
                for(int j = ((i * (i + 3) << 1) + 3), p = (i << 1) + 3; j < limit; j += p){
                    isPrime[j] = false;
                }
            }
        }
        return isPrime;
    }
}

Solution

In the code:

if (index != 0){
    System.out.println(index);
 }else{
    System.out.println(-1);
}


Using a ternary reduces clutter and improves readibility:

System.out.println(index == 0 ? -1 : index);

Code Snippets

if (index != 0){
    System.out.println(index);
 }else{
    System.out.println(-1);
}
System.out.println(index == 0 ? -1 : index);

Context

StackExchange Code Review Q#97366, answer score: 3

Revisions (0)

No revisions yet.