Skip to content
Advertisement

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

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);
    }
}

Advertisement

Answer

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
Advertisement