Problem:
Write a program that reads an integer n and checks whether n is a power of 2 (powers of 2 are 1,2,4,8,16,32, …). The output of your program is either “yes” or “no”.
Solution:
import java.util.Scanner;
public class lauprob4
{
public static void main (String[] args)
{
//Simple scanning of the number
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer: ");
int n = scan.nextInt();
//Of course, a number is a power of n if its
//only divisors are 2 and 1, i.e. n=2^x * 1=2*2*2*2*...*1
//this will make us exit the loop the second we find
// out that the number isn't (still) divisible by 2
//such as 8 which is a power of 2 and will eventually be
//equal to one since with this loop 8 becomes 4, 2, then 1
//Conversely, if it's not a power of two then we'll come out anyway
// such as 6 becomes 3 which isn't divisible by 2 and so we exist
//In any case we're gonna exit the loop eventually
while (n % 2 == 0)
{
//We just keep on dividing the number by 2 till we get out
till we n /= 2;
}
//If our number really is a power of 2
//then we'll eventually have to reach 1
//for example, 16 becomes 8 which becomes 4
//which becomes 2 which becomes 1
if (n == 1)
System.out.println(n + " is a power of two");
//if the number isn't a power of two, then the loop
//would've changed the number to a number that isn't one
else
System.out.println(n + " is not a power of two");
}
}
No comments :
Post a Comment