Pritom Mazumdar
Pritom Mazumdar

Reputation: 335

Number of times all the numbers in an array are divisible by 2

I am trying to get the count of number of times all the integers in an array is divisible by 2 considering only one integer in each step. For example, initially if I have the array : [2,4,2] and count = 0

Step 1

[1,4,2] , count=1

Step 2

[1,2,2] , count=2

Step 3

[1,1,2] , count=3

Step 4

[1,1,1] , count=4

My approach to the problem is given below :

Code

public static void main(String[] args) {
     int[] ar={2,4,2};
     int[] p=new int[ar.length];
     int count=0;
     for (int i=0;i<ar.length ;i++ ) {
        if(ar[i]>=1){
            ar[i]=ar[i]/2;
            count++;
        }
     }
     for (int x:ar) {
        System.out.println(x);
     }
     System.out.println("Count:"+count);

}

Output

1
2
1
Count:3

The problem in the code given above is that the array is scanned only one time and I want to scan the array until all the integers are no more divisible by 2

Upvotes: 3

Views: 828

Answers (2)

Eran
Eran

Reputation: 393781

Note that you have two issues:

  1. You divide each element of the array by 2 at most one time.
  2. You divide elements of the array by 2 without checking first whether or not they are divisible by 2.

You need an inner loop that would divide each array element as long as it is divisible by 2:

public static void main(String[] args) {
     int[] ar={2,4,2};
     int[] p=new int[ar.length];
     int count=0;
     for (int i=0;i<ar.length ;i++ ) {
        while (ar[i] % 2 == 0 && ar[i] > 0) { // keep dividing ar[i] by 2 as long as 
                                              // it is divisible by 2
            ar[i]=ar[i]/2;
            count++;
        }
     }
     for (int x:ar) {
        System.out.println(x);
     }
     System.out.println("Count:"+count);
}

Upvotes: 1

Vinayak Singla
Vinayak Singla

Reputation: 142

     for (int i=0;i<ar.length ;i++ ) {
        while(ar[i]%2==0 && ar[i]>1){
            ar[i]=ar[i]/2;
            count++;
        }
     }

This will suffice.

Upvotes: 1

Related Questions