Power of a prime number r in n! in C++

C++Server Side ProgrammingProgramming

<p style="">In this problem, we are given two integer n and r. Our task is to find the power of the given prime number r in the factorial of the number n.</p><p>Let&rsquo;s take an example to understand the problem</p><p><strong>Input</strong> &minus; n = 6 r = 2</p><p><strong>Output</strong> &minus; 4</p><p style=""><strong>Explanation</strong> &minus;</p><pre class="result notranslate" style="">Factorial n, 6! = 6*5*4*3*2*1 = 720 720 = 2<sup>4</sup> * 3<sup>2</sup> * 5, power of 2 is 4</pre><p>To solve this problem, a simple solution would be directly finding the factorial and then finding the power of the prime number. But this is not the best solution.</p><p>Another efficient solution is using a formula,</p><p>Power of &lsquo;r&rsquo; in n! = floor(n/r) + floor(n/r2) + floor(n/r3) + ...</p><h2>Example</h2><p>Program to show the implementation of our solution,</p><p><a class="demo" href="http://tpcg.io/4PJVxPLd" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">#include &lt;iostream&gt; using namespace std; int primePower(int n, int r) { &nbsp; &nbsp;int count = 0; &nbsp; &nbsp;for (int i = r; (n / i) &gt;= 1; i = i * r) &nbsp; &nbsp; &nbsp; count = count+n/i; &nbsp; &nbsp;return count; } int main() { &nbsp; &nbsp;int n = 6, r = 2; &nbsp; &nbsp;cout&lt;&lt;&quot;Power of prime number &quot;&lt;&lt;r&lt;&lt;&quot;in factorial &quot;&lt;&lt;n&lt;&lt;&quot; is : &quot;&lt;&lt;primePower(n, r); &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><pre class="result notranslate">Power of prime number 2in factorial 6 is : 4</pre>
raja
Updated on 17-Apr-2020 06:49:39

Advertisements