# AND Product

# AND Product

+ 4 comments Simple O(1) solution:

XOR a and b. Find its next power of 2. Subtract 1. Flip its bits and AND with either a or b.a & ~(nextpowerof2(a^b)-1)

That's it.

+ 0 comments I think there is weak test cases for this problem.After solving this problem, I check many solutions which get accepted just by checking if both A and B have same bitlenght or not, If they have then they wrote A as answer otherwisw 0. But , such solutions fails on case A=26 and B=29. As answer should be : 24 not 26. So, I would like Judges rejudge the submissions after adding some critical cases. Thanks in advance.

+ 7 comments we dont need to & all numbers from a to b.. Just a&(a+1)&(a+2)&(a+4)&(a+8)&(a+16)&(a+32)&(a+64) and so on. As a digit at each place will be surely flipped after 2^(its position) consecutive numbers. We just need to be sure of a zero somwhere so that we can put a zero at same place in our answer. This method will take maximum of 32 iterations. eg: 11 20 11&12&13&15&19 Thats it

+ 3 comments long long int i,a,b,and,t; scanf("%lld",&t); while(t>0) {

`scanf("%lld%lld",&a,&b); and=a; for(i=a+1;i<=b;i++) { and=and&(i); } printf("%lld\n",and); t--; } return 0;`

} i am getting time out in testcase 8 and test case 9 all other test case are running perfectly please suggest me how to overcome that with explanation please as soon as possible.

+ 1 comment java sol :

import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t=in.nextInt(); while(t-->0){ long a=in.nextLong(); long b=in.nextLong(); long res=a&(a+1); int i=1; while(a+(long)Math.pow(2,i)<=b){ res = (a+(long)Math.pow(2,i))&res; ++i; } System.out.println(res&b); }}}

Sort 175 Discussions, By:

Please Login in order to post a comment