[Solved] countNumbers Given an array and two numbers L and R, the task is to write a program which prints the count of numbers in the given range with Java

countNumbers: Given an array and two numbers L and R, the task is to write a program which prints the count of numbers in the given range L – R which are divisible by all the numbers in the array. 

Suppose the given array is arr[] = {1, 2, 3, 5} and the range is 1 – 30, then there is only one number(30) in this range that is divisible by all the elements of the array, so the output will be 1.

Input:

4
1 2 3 5
1 30

Output:

1

Solution

import java.util.*;
class Perfectice 
{ 
  static int countNumbers(int arr[], int n, int l, int r) 
  { 
    //write your code here
    int count = 0;
    for (int i = l; i <= r; i++) {
      boolean flag = true;
      for (int j = 0; j < n; j++) {
        if (i % arr[j] != 0) {
          flag = false;
          break;
        }
      }
      if (flag) {
        count++;
      }
    }
    return count;
  } 
  public static void main(String args[]) 
  { 
    int n,l,r;
    Scanner sc = new Scanner(System.in);
    n=sc.nextInt();
    int arr[] = new int[n];
    for(int i=0;i<n;i++)
      arr[i] = sc.nextInt();
    l = sc.nextInt();
    r = sc.nextInt();
    System.out.println(countNumbers(arr, n, l, r)); 
  } 
}

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *