How can you print all the powers of two up to a given number in Java?

  • Topic: Comp Sci 
  • Thread starter Thread starter Hiche
  • Start date Start date
  • Tags Tags
    Java
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
6 replies · 4K views
Hiche
Messages
82
Reaction score
0

Homework Statement



Write a program that takes a command line argument integer M and prints all the positive integers that are powers of 2 and less than or equal to M.

Homework Equations



for loops; if conditional.

The Attempt at a Solution



Code:
public class PowersOfTwo
{
	public static void main(String[] args)
	{
		int m = Integer.parseInt(args[0]);

		for (int i = 0; i <= m ; i++)
		{
			if (Math.pow(2, i) <= m)
				System.out.println(Math.pow(2, i));
		}
	}
}

Is this true and answers the problem? Why are the values printed in type double rather than integer? Like so, when I input 4 in the command-line:

1.0
2.0
4.0


And is there another way to do that using boolean? How do you check if an integer is a power of two? Do you use the modulus or what?
 
Physics news on Phys.org
Because the pow method returns a double, not an int.

You can do this without using the pow method, by instead using nothing more complicated that multiplication.
2 = 21 = 2
4 = 22 = 2*2
8 = 23 = 2*2*2
and so on.
 
Code:
public class Power
{
	public static void main(String[] args)
	{
		int n = Integer.parseInt(args[0]);
		int a = 2;

		for (int i = 1; i <= n ; i++)
		{
			a = a * 2;
			if (a <= n)
			{
				System.out.println(a);
			}
		}
	}
}

Is this fine? Whenever I input a number like 99, it works fine for the first couple of values then a negative number appears and a series of 0s appear out of nowhere.
 
You should have some logic in your loop so that it exits after a > n.

Try this.
Code:
for (int i = 1; i <= n ; i++)
{
   a = a * 2;
   if (a <= n)
   {
      System.out.println(a);
   }
   else
   {
      break;
   }
}
 
Your version worked, but I did this:

Code:
public class Power
{
	public static void main(String[] args)
	{
		int n = Integer.parseInt(args[0]);
		int a = 1;

		for (int i = 1; i <= n * i / a; i++)
		{
			a = a * 2;
			if (a <= n)
			{
				System.out.println(a);
			}
		}
	}
}

..and it worked. I unintentionally did that, though; the i <= n * i /a.
 
I like my solution better because it is simpler. A simpler solution is usually better than a clever solution, because it will be easier for some other person reading your code to understand.