4

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");
            }
        }
    }
}

5 Answers5

7

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)) {
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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.

Community
  • 1
  • 1
Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
0

If the long number range is enough, you can just change

n = sc.nextInt();

to

n = sc.nextLong();

At the moment, n is only set to an integer and therefore limited to the int number range.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

Better Use Class BigInteger it implement Serializable, Comparable<BigInteger> .BigInteger provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.

input="Number"
BigInteger number = new BigInteger(input);
//Do your stuff

Happy to help thanks

Anand Dwivedi
  • 1,452
  • 13
  • 23
0

Take the input in long:

 k = sc.nextLong();
MrAP
  • 223
  • 4
  • 18