3

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

Pritom Mazumdar
  • 325
  • 5
  • 20
  • "I want to scan the array until all the integers are greater than or equal to 1" - but they're already all greater than or equal to 1 from the very beginning, and they remain that way. – user2357112 Sep 24 '17 at 05:37
  • I have edited the question, I want the `array` simplified such that no more `integers` are divisible by 2. – Pritom Mazumdar Sep 24 '17 at 05:41

2 Answers2

1

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);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1
     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.

Vinayak Singla
  • 142
  • 1
  • 12