Powers of 2 without a Zero


Interesting. The Intro to Programming Students gave a crack at this one; and after 30 minutes all were close and half had it. Some worked in Python (easier large numbers and string manipulation) and some in Java (muuuuch faster). Here’s my Java (BlueJ) code. It checks all powers of 2 up to 2^10,000, and then it prints out the counts of all the digits 0-9. The digits are spread out pretty evenly.

import java.math.BigInteger;
public class Powersof2
{
    public int[] digits = new int[11];;
    public Powersof2()
    {
        BigInteger number = new BigInteger ("1");;
        int power = 1;
        
        for (int i = 0; i < digits.length; i++)
        {
            digits[i]=0;
        }
        
        while (power <= 10000)
        {
            number = number.multiply(new BigInteger ("2"));
            
            if (HasAZeroInIt(number))
            {
                System.out.println("Next power of 2 is " + number + " with an exponent of " + power);
            }
            
            
            power += 1;
        }
        
        for (int i = 0; i < digits.length-1; i++)
        {
            System.out.println("index " + i + " and number of digits is " + digits[i]);
        }
                   
       
    }
    
    public boolean HasAZeroInIt(BigInteger n)
    {
        String strn = String.valueOf(n);
        
        int index = 0;
        while (index < strn.length())
        {
            digits[Character.getNumericValue(strn.charAt(index))] += 1;
            index += 1;
        }
        index = 0;
        while (index < strn.length())
        {
            if (strn.charAt(index) == '0')
            {
                return false;
            }
            index += 1;
        }
        return true;
    }    
}

Leave a Reply

Your email address will not be published. Required fields are marked *