The for-loop The product of numbers from a to b

Viewed 1550

I need to write a program that prints the product of all integer numbers from a to b (a < b).

Include a and exclude b from the product.

Sample Input 1:

1 2

Sample Output 1:

1

Your code output:

2

Here is my code:

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        long multiply = 0;

        for(long i = a; i<b; i++){
            multiply = i * (i+1);
        }
            System.out.println(multiply);
    }
}

What I'm doing wrong? Please a hint :)

UPDATE:

It didn't help either.

Test input:

1 2

Correct output:

1

Your code output:

0

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        long multiply = 0;
        for(long i = a+1; i<b; i++){
            multiply = i * (i+1);
            if(multiply==2){
                --multiply;
            }

        }
            System.out.println(multiply);
    }
}
2 Answers

You should start with multiply = 1 and then keep multiplying it with the next integers.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        long multiply = 1;

        for (long i = a; i < b; i++) {
            multiply *= i;
        }
        System.out.println(multiply);
    }
}

A sample run:

1 2
1

Another sample run:

2 5
24

Let's try to work out the solution before writing code & understand what "product of all integer numbers from a to b (a < b)" is

For a = 1 and b = 2, because we're including 1 and excluding 2, the result is 1 Likewise, for a = 1 and b = 3, result is 1 * 2

So your first implementation is actually close: you'd want to loop through all number included in the result and accumulate those number by multiplication. You wouldn't want just multiply = i * (i+1); because it will replace the value of multiply in each loop iteration, instead you should use the previous value of multiply and combine it with i

Related