Check if a number is power of k using base changing methods in C++

C++Server Side ProgrammingProgramming

<p>Here we will see a program, if one number is given, another value k is also given, we have to check whether the number is power of k or not. But we have to perform the base changing method to solve this problem. Suppose a number is 27, and k = 3. Then by base changing method, the 27 will be 10003. Here after changing the base if there is only one occurrence of digit 1, and others are 0, then the number is power of k.</p><p>To solve this problem, we will follow these steps.</p><p><strong>Steps&nbsp;</strong>&minus;</p><ul class="list"><li>define flag := false</li><li>while number &gt; 0, repeat steps 3 to 6</li><li>find digit := number mod k</li><li>if the digit &gt; 1, then return false</li><li>otherwise when digit is 1, then if the flag is True, return false, otherwise flag := true.</li><li>set number := number / k.</li><li>return true</li></ul><h2>Example</h2><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;iostream&gt; #include &lt;cmath&gt; using namespace std; bool isPowerOfK(int num, int k) { &nbsp; &nbsp;bool flag = false; &nbsp; &nbsp;while (num &gt; 0) { &nbsp; &nbsp; &nbsp; int digit = num % k; //get current digit in base k &nbsp; &nbsp; &nbsp; if (digit &gt; 1) //if the digit is not 0 or 1, then it is not power of k &nbsp; &nbsp; &nbsp; return false; &nbsp; &nbsp; &nbsp; if (digit == 1) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (flag) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;flag = true; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; num /= k; &nbsp; &nbsp;} &nbsp; &nbsp;return true; } int main() { &nbsp; &nbsp;int number = 27, K = 3; &nbsp; &nbsp;if(isPowerOfK(number, K)){ &nbsp; &nbsp; &nbsp; cout &lt;&lt; number &lt;&lt; &quot; is power of &quot; &lt;&lt; K; &nbsp; &nbsp;} else { &nbsp; &nbsp; &nbsp; cout &lt;&lt; number &lt;&lt; &quot; is not power of &quot; &lt;&lt; K; &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">27 is power of 3</pre>
Updated on 22-Oct-2019 06:39:10