- #1
Hiche
- 84
- 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?