Note that there are some explanatory texts on larger screens.

plurals
  1. POBinary decomposition in C
    text
    copied!<p>I am coding something to decompose a number in binary on a training site. I have test it a hundred of times on my local compiler, it works just fine, but the training site tells me there are errors. </p> <p>(My code is nor elegant nor efficient, especially the loop but I decomposed the code to understand where the error could be). Could anybody tell me if there is an error ?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; //function that displays the greatest power of 2 less than a fixed number N int residu(int N) { int i; int M=2; for(i=0;i&lt;N;i++){ if(M&gt;N){break;}else{M=2*M;i++;} } return M/2; } int main() { int i; //N is the input to decompose int N; scanf("%d",&amp;N); //We will search for the greatest power of 2 less than a fixed number N, //than repeating the some process with the residue of N with the greatest power of 2 //less than N, so we have to store the value of N for the loop (see below) we will use to work //correctly int M; M=N; //D displays the diffrence betwenn two successive powers of 2 that appears in the //binary decomposition, (we will then print "O") int D; D=log(residu(N))/log(2); for(i=0;i&lt;M;i++){ //If N==residu(N), the decomposition is finished if(N==residu(N)){printf("1");int k; for(k=0;k&lt;D;k++){printf("0");}break;} else{ // N is a the residue of the former value of N and the greatest power of 2 //less than N N=N-residu(N); D=D-log(residu(N))/log(2); printf("1"); int k; for(k=0;k&lt;D-1;k++){printf("0"); } D=log(residu(N))/log(2); } } } </code></pre>
 

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