javamath

Sum the products of numbers in range <a, b> that digits are prime number


I have got a little problem—I need to prepare program that (step by step information):
1)Gets from user two integers a and b and stop when b>a
2)Sum the products off all numbers in range < a, b > that digits are prime numbers
Example:
Input: 10, 15,
Output: 2340 (because 12*13*15 = 2340 2, 3 and 5 are prime numbers)

I feel like I stuck—I have got only a sum of the numbers (not the product) and not the prime but all of them.

public class Ex4 {
    static int getNmbs() {
        System.out.println("Enter number:");
        Scanner sc = new Scanner(System.in);
        return sc.nextInt();
    }
    public static int getSum(int a, int b) {
        if (a > b)
            return 0;
        else
            return a + getSum(a + 1, b);
    }

    public static void main(String[] args) {
        int a = getNmbs();
        int b = getNmbs();
        int c =getSum(a,b);
        System.out.println(c);
    }
}

Solution

  • In order to solve this problem, you need to think of the step by step process: First, accept two integer inputs, a and b.

    Declare a variable to hold your product (the answer) and initialize it at 1. (If you initialize it at 0, then you will always get 0)

    Now, assuming a < b, check to see if the digits of a are prime. IF it is, multiply your product by it and increment a. If it isn't, just increment a.

    Rinse and repeat until a > b. And return the final product.

    The trick here is going to be figuring out a way to check if the digits of a number are prime. I suggest using modulo division in increments of powers of 10 (for those more mathematically inclined) or converting the integer to a String and checking each character (using toCharArray).

    Hope this helps!