Im trying out a bitwise And program for the range of number between a and b .
Can have 'n' testcases for that.
0<=a,b<=2^32
1<=n<=200
EXPLANATION :
1
2 4
computation : 2&3&4
INPUT :
1
4009754624 4026531839
OUTPUT:
Exception in thread "main" java.lang.StackOverflowError at Example.BitwiseAnd.calculate(BitwiseAnd.java:78)
CODE :
public class BitwiseAnd
{
static long temp = 0;
static long result[];
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int time = scan.nextInt();
if(validateTime(time))
{
result = new long[time];
for(int i=0;i<time;i++)
{
long arr[] = new long[2];
arr[0] = scan.nextLong();
temp=arr[0];
arr[1] = scan.nextLong();
if(validateNum(arr[0],arr[1]))
{
result[i] = calculateUsingRecursion(arr[0],arr[1]);
//result[i] = calculateUsingForLoop(arr[0],arr[1]);
}
else
{
System.out.println("Enter a valid numbers");
}
}
printResult(result);
}
else
{
System.out.println("Enter a valid number of testcases");
}
}
public static void printResult(long[] result)
{
for(int i=0;i<result.length;i++)
{
System.out.println(result[i]);
}
}
public static boolean validateNum(long num1, long num2)
{
Long max = (long)Math.pow(2, 32);
if(num1<0 || num1>max)
{
return false;
}
else if(num2<0 || num2>max)
{
return false;
}
return true;
}
public static boolean validateTime(int time)
{
if(time<1 || time>200)
{
return false;
}
return true;
}
private static long calculateUsingRecursion(long num1, long num2)
{
while(num1<num2)
{
num1=num1+1;
temp=temp&num1;
calculateUsingRecursion(num1, num2);
}
return temp;
}
private static long calculateUsingForLoop(long num1,long num2)
{
num1=num1+1;
for(long i=num1 ; i<=num2 ; i++)
{
temp=temp&num1;
}
return temp;
}
}
the recursive method computation is throwing me StackOverFlowException , for large set of numbers. Whereas the for loop works fine . My question here is why couldn't we have recursion for the huge set of inputs? And how it could be fixed with recursion ?