Search code examples
javaparseint

Adding int A plus the product of the individual numbers A is made of


Okay so I am writing a program that will ask the user for two numbers.

n = the starting number of a sequence.
k = the length of the sequence.

I want the next number to equal the previous number plus the product of that number's digits.

this is what i have. I want to use a parseInt but not sure how

public class John

{

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int initial_num, output_seq;

        while(true)
        {
            System.out.print("Enter n and k: ");
            initial_num = sc.nextInt();
            output_seq = sc.nextInt();

            if(initial_num != 0 || output_seq != 0)
                System.out.println(nextNum(initial_num, output_seq));
            else
                break;
        }
    }

    static int nextNum(int input, int output)
    {
        int first = input;
        int seq_num = output;
        int next_num = 0;

        for (int k = 0; k < seq_num; k++)
        {
            next_num = first + ( * );
        }
        return next_num;
    }

}

I'm not sure how write the product.


Solution

  • To generate the product of the digits of a number, use the properties of decimal numbers. In other words, divide by ten and take the remainder (modulo 10). There is no need to turn it to a string and take individual characters and convert those to integers.

    public long digitProduct (long anInteger) throws Exception {
        if (anInteger <= 0) {
            throw new Exception ("digitProduct:  input integer " + anInteger +
                " is less than or equal to zero.");
        }
        long product = 1;
        do {
            product = product * (anInteger % 10);  // modulo 10 is last digit.
            anInteger = anInteger / 10;  // Shifts out last digit.
        } while (anInteger > 0);
        return product;
    } // digitProduct (long)
    

    Use longs because the product could get large very quickly. Consider using BigInteger.