Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I wrote this program to find if a given input is power of 2 , this program is not running for very large number such as 10^18 or so. what should i do

Tags:

java

int

This is a program to check if an input is power of 2 or not. This program is running fine for inputs up to 8 digits but when I am giving input like 1018, it is not working, What should I do?

import java.util.Scanner;
    public class search {
        public static void main(String [] args){
            //to take how many inputs are there
            Scanner sc = new Scanner(System.in);
            int k ;
            k = sc.nextInt();
            for(int i = 0 ;i<k;i++){
            // input number n
            long  n ;


            n = sc.nextInt();

            if ((n > 0) && ((n & (n - 1)) == 0)){
                System.out.println("YES");
            }
            else{
                System.out.println("NO");
            }
        }
    }
}
like image 579
Inder Mishra Avatar asked Feb 09 '23 04:02

Inder Mishra


2 Answers

The problem is that 1018 is out of range of Java int, which stores numbers up to 231-1, or roughly 2*109. You can expand the range of your program by using long in place of int to accept numbers up to 9*1018, or to make it accept virtually unlimited range by using BigInteger:

BigInteger n = new BigInteger(numericString);
BigInteger test = n.and(n.subtract(BigInteger.ONE));
if (test.equals(BigInteger.ZERO)) {
    ...
}
like image 196
Sergey Kalinichenko Avatar answered Feb 14 '23 00:02

Sergey Kalinichenko


You need to get your input number as String then use BigInteger class to avoid limit surpassing problem,

BigInteger inputNumber = new BigInteger(inputString);

Also, refer What does BigInteger having no limit mean? to know more about BigInteger limits.

like image 25
Sabir Khan Avatar answered Feb 14 '23 00:02

Sabir Khan