{"id":63373,"date":"2020-08-28T06:10:03","date_gmt":"2020-08-28T06:10:03","guid":{"rendered":"https:\/\/www.baeldung.com\/?p=86285"},"modified":"2020-08-28T06:10:03","modified_gmt":"2020-08-28T06:10:03","slug":"largest-power-of-2-that-is-less-than-the-given-number","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2020\/08\/28\/largest-power-of-2-that-is-less-than-the-given-number\/","title":{"rendered":"Largest Power of 2 That Is Less Than the Given Number"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<h2 data-id=\"overview\">1. Overview<\/h2>\n<div class=\"bd-anchor\" id=\"overview\"><\/div>\n<p>In this article, we&#8217;ll be seeing how to find the largest power of 2 that is less than the given number.<\/p>\n<p>For our examples, we&#8217;ll take the sample input 9. 2<sup>0<\/sup> is 1, the least valid input for which we can find the power of 2 less than the given input is 2. Hence we&#8217;ll only consider inputs greater than 1 as valid.<\/p>\n<h2 data-id=\"naive-approach\">2. Naive Approach<\/h2>\n<div class=\"bd-anchor\" id=\"naive-approach\"><\/div>\n<p>Let&#8217;s start with 2<sup>0<\/sup>, which is 1, and we&#8217;ll <strong>keep multiplying the number by 2 until we find a number that is less than the input<\/strong>:<\/p>\n<pre><code class=\"language-java\">public long findLargestPowerOf2LessThanTheGivenNumber(long input) {\r\n    Assert.isTrue(input &gt; 1, \"Invalid input\");\r\n    long firstPowerOf2 = 1;\r\n    long nextPowerOf2 = 2;\r\n    while (nextPowerOf2 &lt; input) {\r\n        firstPowerOf2 = nextPowerOf2;\r\n        nextPowerOf2 = nextPowerOf2 * 2;\r\n    }\r\n    return firstPowerOf2;\r\n}<\/code><\/pre>\n<p>Let&#8217;s understand the code for sample <em>input<\/em> = 9.<\/p>\n<p>The initial value for <em>firstPowerOf2<\/em> is 1 and <em>nextPowerOf2<\/em> is 2. As we can see, 2 &lt; 9 is true, and we get inside the while loop.<\/p>\n<p>For the first iteration, <em>firstPowerOf2<\/em> is 2 and <em>nextPowerOf2<\/em> is 2 * 2 = 4. Again 4 &lt; 9 so lets continue the while loop.<\/p>\n<p>For the second iteration, <em>firstPowerOf2<\/em> is 4 and <em>nextPowerOf2<\/em> is 4 * 2 = 8. Now 8 &lt; 9, let&#8217;s keep going.<\/p>\n<p>For the third iteration, <em>firstPowerOf2<\/em> is 8 and <em>nextPowerOf2<\/em> is 8 * 2 = 16. The while condition 16 &lt; 9 is false, so it breaks out of the while loop. 8 is the largest power of 2 which is less than 9.<\/p>\n<p>Let&#8217;s run some tests to validate our code:<\/p>\n<pre><code class=\"language-java\">assertEquals(8, findPowerOf2LessThanTheGivenNumber(9));\r\nassertEquals(16, findPowerOf2LessThanTheGivenNumber(32));\r\n<\/code><\/pre>\n<p><strong>The time complexity of our solution is O(log<sub>2<\/sub>(N))<\/strong>. In our case, we iterated log<sub>2<\/sub>(9) = 3 times.<\/p>\n<h2 data-id=\"using-mathlog\">3. Using <em>Math.log<\/em><\/h2>\n<div class=\"bd-anchor\" id=\"using-mathlog\"><\/div>\n<p>Log base 2 will give how many times we can divide a number by 2 recursively in other words, <strong>log<sub>2<\/sub> of a number gives the power of 2<\/strong>. Let&#8217;s look at some examples to understand this.<\/p>\n<p>log<sub>2<\/sub>(8) = 3 and log<sub>2<\/sub>(16) = 4. In general, we can see that y = log<sub>2<\/sub>x where x = 2<sup>y<\/sup>.<\/p>\n<p>Hence, if we find a number that is divisible by 2, we subtract 1 from it so that we avoid a scenario where the number is a perfect power of 2.<\/p>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-lang-math\"><em>Math.log<\/em><\/a> is log<sub>10<\/sub>. To compute log<sub>2<\/sub>(x), we can use the formula log<sub>2<\/sub>(x)=log<sub>10<\/sub>(x)\/log<sub>10<\/sub>(2)<\/p>\n<p>Let&#8217;s put that in code:<\/p>\n<pre><code class=\"language-java\">public long findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(long input) {\r\n    Assert.isTrue(input &gt; 1, \"Invalid input\");\r\n    long temp = input;\r\n    if (input % 2 == 0) {\r\n        temp = input - 1;\r\n    }\r\n    long power = (long) (Math.log(temp) \/ Math.log(2));\r\n    long result = (long) Math.pow(2, power);\r\n    return result;\r\n}<\/code><\/pre>\n<p>Assuming our sample input as 9, the initial value of <em>temp<\/em> is 9.<\/p>\n<p>9 % 2 is 1, so our <em>temp<\/em> variable is 9.<strong>\u00a0<\/strong>Here we are using modulo division, which will give the remainder of 9\/2.<\/p>\n<p>To find the log<sub>2<\/sub>(9), we do log<sub>10<\/sub>(9) \/ log<sub>10<\/sub>(2) = 0.95424 \/ 0.30103 ~= 3.<\/p>\n<p>Now, the <em>result<\/em> is 2<sup>3<\/sup> which is 8.<\/p>\n<p>Let&#8217;s verify our code:<\/p>\n<pre><code class=\"language-java\">assertEquals(8, findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(9));\r\nassertEquals(16, findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(32));<\/code><\/pre>\n<p>In reality, <em>Math.pow<\/em> will be doing the same iteration that we did in approach 1. Hence we can say that for this solution too, <strong>the time complexity is O(Log<sub>2<\/sub>(N))<\/strong>.<\/p>\n<h2 data-id=\"bitwise-technique\">4. Bitwise Technique<\/h2>\n<div class=\"bd-anchor\" id=\"bitwise-technique\"><\/div>\n<p>For this approach, we&#8217;ll use the bitwise shift technique. First, let&#8217;s look at the binary representations for the power of 2 considering we have 4 bits to represent the number<\/p>\n<table width=\"250\">\n<tbody>\n<tr>\n<td>2<sup>0<\/sup><\/td>\n<td>1<\/td>\n<td><em>0001<\/em><\/td>\n<\/tr>\n<tr>\n<td>2<sup>1<\/sup><\/td>\n<td>2<\/td>\n<td><em>0010<\/em><\/td>\n<\/tr>\n<tr>\n<td>2<sup>2<\/sup><\/td>\n<td>4<\/td>\n<td><em>0100<\/em><\/td>\n<\/tr>\n<tr>\n<td>2<sup>3<\/sup><\/td>\n<td>8<\/td>\n<td><em>1000<\/em><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Looking closely, we can observe that we can <strong>compute the power of 2 by left shifting the bytes for 1<\/strong>. ie. 2<sup>2<\/sup> is left shift bytes for 1 by 2 places and so on.<\/p>\n<p>Let&#8217;s code using bitshift technique:<\/p>\n<pre><code class=\"language-java\">public long findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(long input) {\r\n    Assert.isTrue(input &gt; 1, \"Invalid input\");\r\n    long result = 1;\r\n    long powerOf2;\r\n    for (long i = 0; i &lt; Long.BYTES * 8; i++) {\r\n        powerOf2 = 1 &lt;&lt; i;\r\n        if (powerOf2 &gt;= input) {\r\n            break;\r\n        }\r\n        result = powerOf2;\r\n    }\r\n    return result;\r\n}<\/code><\/pre>\n<p>In the above code, we are using <em>long <\/em>as our data type, which uses 8 bytes or 64 bits. So we&#8217;ll be computing the power of 2 up to 2<sup>64<\/sup>. We are using the bit shift operator <em>&lt;&lt; <\/em>to find the power of 2. For our sample input 9, after the 4<sup>th<\/sup> iteration, the value of <em>powerOf2<\/em> = 16 and <em>result<\/em> = 8 where we break out of the loop as 16 &gt; 9 the <em>input<\/em>.<\/p>\n<p>Let&#8217;s check if our code is working as expected:<\/p>\n<pre><code class=\"language-java\">assertEquals(8, findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(9));\r\nassertEquals(16, findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(32));<\/code><\/pre>\n<p>The <strong>worst-case time complexity for this approach is again O(log<sub>2<\/sub>(N))<\/strong>, similar to what we saw for the first approach. However, this approach is better as a <strong>bit shift operation is more efficient compared to multiplication<\/strong>.<\/p>\n<h2 data-id=\"bitwise-and\">5. Bitwise AND<\/h2>\n<div class=\"bd-anchor\" id=\"bitwise-and\"><\/div>\n<p>For our next approach, we&#8217;ll be using this formula <strong>2<sup>n<\/sup> AND 2<sup>n<\/sup> -1 = 0<\/strong>.<\/p>\n<p>Let&#8217;s look at some examples to understand how it works.<\/p>\n<p>The binary representation of 4 is <em>0100,<\/em> and 3 is <em>0011<\/em>.<\/p>\n<p>Let&#8217;s do a <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-bitwise-operators\">bitwise AND operation<\/a> on these two numbers. <em>0100<\/em> AND <em>0011<\/em> is <em>0000<\/em>. We can say the same for any power of 2 and a number less than it. Let&#8217;s take 16 (2<sup>4<\/sup>) and 15 which is represented as <em>1000<\/em>, <em>0111<\/em> respectively. Again, we see that the bitwise AND on these two results in 0. We can also say that the AND operation on any other number apart from these 2 won&#8217;t result in a 0.<\/p>\n<p>Let&#8217;s see the code for solving this problem using bitwise AND:<\/p>\n<pre><code class=\"language-java\">public long findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(long input) { \r\n    Assert.isTrue(input &gt; 1, \"Invalid input\");\r\n    long result = 1;\r\n    for (long i = input - 1; i &gt; 1; i--) {\r\n        if ((i & (i - 1)) == 0) {\r\n            result = i;\r\n            break;\r\n        }\r\n    }\r\n    return result;\r\n}<\/code><\/pre>\n<p>In the above code, we loop over numbers less than our input. Whenever we find the bitwise AND of a number and number-1 is zero, we break out of the loop, as we know that number will be a power of 2. In this case for our sample <em>input<\/em> 9, we break out of the loop when <em>i<\/em> = 8 and <em>i<\/em> &#8211; 1 = 7.<\/p>\n<p>Now, let&#8217;s verify a couple of scenarios:<\/p>\n<pre><code class=\"language-java\">assertEquals(8, findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(9));\r\nassertEquals(16, findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(32));<\/code><\/pre>\n<p>The worst-case <strong>time complexity for this approach is O(N\/2)<\/strong> when the input is an exact power 2. As we can see, this is not the most efficient solution, but it is good to know this technique as it could come handy when tackling similar problems.<\/p>\n<h2 data-id=\"conclusion-1\">6. Conclusion<\/h2>\n<div class=\"bd-anchor\" id=\"conclusion-1\"><\/div>\n<p>We have seen different approaches for finding the largest power of 2 that is less than the given number. We also noticed how bitwise operations can simplify computations in some cases.<\/p>\n<p>The complete source code with unit tests for this article can be found <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/core-java-modules\/core-java-lang-math-2\">over on GitHub<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/634675366\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Share on Google+\" href=\"https:\/\/feeds.feedblitz.com\/_\/30\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/googleplus20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/634675366\/baeldung,\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-largest-power-of-2-less-than-number#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-largest-power-of-2-less-than-number\/feed\/\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>Learn how to find the largest power of 2 that is less than an input number.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>&nbsp;<a title=\"Share on Google+\" href=\"https:\/\/feeds.feedblitz.com\/_\/30\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/googleplus20.png\"><\/a>&nbsp;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/634675366\/baeldung,\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>&nbsp;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\"><\/a>&nbsp;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>&nbsp;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/634675366\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>&nbsp;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-largest-power-of-2-less-than-number#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&nbsp;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-largest-power-of-2-less-than-number\/feed\/\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&nbsp;<\/div>\n<\/div>","protected":false},"author":214,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"Largest Power of 2 That Is Less Than the Given Number - ITTeacherITFreelance.hk","description":"Learn how to find the largest power of 2 that is less than an input number. &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"},"footnotes":""},"categories":[6],"tags":[4911,4912],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/63373"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/214"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=63373"}],"version-history":[{"count":9,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/63373\/revisions"}],"predecessor-version":[{"id":66530,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/63373\/revisions\/66530"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=63373"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=63373"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=63373"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}