Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ clock() behaving weirdly with recursive function
    text
    copied!<p>Here's a simple program I wrote to find all the non-decreasing-digit numbers of length &lt;=L whose digits sum upto N. The code works fine, but when I try to clock the run time using clock() from ctime it shows a weird behaviour.</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; #include&lt;ctime&gt; using namespace std; typedef long long int LL; int Sum(LL S){ int sum=0; for(;S;S/=10) sum+=S%10; return sum; } void Generate(LL S, int len, int N, int L, vector&lt;LL&gt; &amp;V){ if(len&lt;L) for(int i=0;i&lt;=9;++i) if(i&gt;=S%10) Generate(S*10+i, len+1, N, L, V); int sum = Sum(S); if(sum!=N) return; else if(sum == N &amp;&amp; len == L){ V.push_back(S); cout &lt;&lt; S &lt;&lt; endl; //Line 4 return; } } int main(){ int N,L; vector&lt;LL&gt; V; LL S; cin &gt;&gt; N &gt;&gt; L; clock_t start=clock(); //Line 1 Generate(S, 0, N, L, V); //clock_t start=clock(); //Line 2 clock_t end = clock(); for(int i=0;i&lt;V.size();++i) cout &lt;&lt; V[i] &lt;&lt; " "; cout &lt;&lt; endl; cout &lt;&lt; "Run time: " &lt;&lt; (double)(end-start)/CLOCKS_PER_SEC; return 0; } </code></pre> <p>I record the no. of clock ticks elapsed before calling the "Generate" function at //Line 1 and I do the same afterwards at //Line 2, the difference of which I believe should give me the no. of clock ticks elapsed in generating the required numbers.</p> <p>But if I do so my function "Generate"'s processing somehow gets affected! It won't output the numbers to stdout(from //Line 4) and even if I pass a vector to store up the generated numbers, it won't store any!</p> <p>However, if I use clock() at //Line 2 my output on stdout is fine and the referenced vector V gets filled up with the desired result. but clock() on //Line 2 is of no use. <br> <br> What I fail to understand is How can a call to clock() affect some processing in 'Generate' function, unless of course I've some obscure Bug! or the clock() is not supposed to be used in this kind of recursive setup?</p> <p>Please help me Debug this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload