Repeated Unit Divisibility using C++

C++Server Side ProgrammingProgramming

<p>In this article, we will discuss finding the number of repeated units divisible by N. Repeated units are the repetitive numbers of 1 only, Let R(k) be the repetitive unit where k is the length of 1&rsquo;s. E.g R(4) = 1111. So we need to find the minimum number of k for which R(k) is divisible by N, for example &minus;</p><pre class="result notranslate">Input : N = 13 Output : k = 6 Explanation : R(6) i.e 111111 is divisible by 13. Input : N = 31 Output : k = 15</pre><h2>Approach to find The Solution</h2><p>You can approach this problem by checking each value for k starting from 1 where R(k) is divisible by N. But with this solution, we will not find whether N is divisible by any value of R(k). This will make the program too complex and maybe not work too.</p><p><strong>An Efficient Approach for the solution of this program is,</strong></p><ul class="list"><li>Check whether N is coprime with 10.</li><li>If NOT, then R(k) will not be divisible by N for any value of k.</li><li>If YES, then for each repetitive unit R(1), R(2), R(3)... and so on, Calculate the remainder of division of R(i) and N, So there will be n number of the remainder.</li><li>Find the same remainder values for R(i) and R(j), where R(i) and R(j) are two repeated units so that R(i) - R(j) will be divisible by N.</li><li>aThe difference of R(i) and R(j) will be repeated unit multiplied by some power of 10, But 10 and N are relatively prime, so R(k) will be divisible by N.</li></ul><h2>Example</h2><pre class="demo-code notranslate language-cpp" data-lang="cpp">#include &lt;bits/stdc++.h&gt; using namespace std; int main() { &nbsp; &nbsp;int N = 31; &nbsp; &nbsp;int k = 1; &nbsp; &nbsp;// checking if N is coprime with 10. &nbsp; &nbsp;if (N % 2 == 0 || N % 5 == 0){ &nbsp; &nbsp; &nbsp; k = 0; &nbsp; &nbsp;} else { &nbsp; &nbsp; &nbsp; int r = 1; &nbsp; &nbsp; &nbsp; int power = 1; &nbsp; &nbsp; &nbsp; // check until the remainder is divisible by N. &nbsp; &nbsp; &nbsp; while (r % N != 0) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;k++; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;power = power * 10 % N; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;r = (r + power) % N; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;cout &lt;&lt; &quot;Value for k : &quot;&lt;&lt; k; &nbsp; &nbsp;return 0; } </pre><h2>Output</h2><pre class="result notranslate">Value for k : 15</pre><h2>Conclusion</h2><p>In this article, we discuss finding the value of k for R(k), where R(k) is the repeated units divisible by given N.We discussed an optimistic way to find the value of k. We also discussed C++ code to solve this problem. You can write this code in any other language like Java, C, Python, etc. We hope you find this article helpful.</p>
Updated on 29-Nov-2021 09:52:43