What does the following function return? (in terms of meaning)
int f(int n){
if(n == 0) return 0;
else return n % 2 + f(n / 2)
}
Tried running the code, but couldn’t find any pattern in the results
This output of this function can be interpreted as the number of 1s (in base 10) when the number n is represented in binary.
The base case is when n == 0, where the number of 1s is 0.
For every other n, there is a recursive call. There are two parts to this. The first, which is n % 2, finds out the last bit of n. If it is a 1, it contributes to the value returned, and is hence, counted. The second part, f(n/2), is computing the number of 1s in all the bits of n except the last bit. This is because n/2 is n with a one bit right shift.
To put it together, the function works as follows. It checks the last bit, and if 1, it adds it to the total. It then performs a recursive call on itself with the last bit removed. This goes on till all bits are removed, which is covered by the base case.
Related
I plan to use this inside a game loop to draw the score using custom bitmap font.
Here is what I have. Now I know that I have used the modulus, division and power operators a bunch of times. I understand that using this in a game loop is not a good thing to do. Any suggestions?
// Get digit n, where n is digit starting from the units place and moving left
int getDigit(int number, int position)
{
return (number % (int)pow(10, position)) / pow(10, (position - 1));
}
If int is 32 bits, then:
static const int table[] =
{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
return number / table[position-1] % 10;
is a reasonable implementation:
It does not invoke pow or use floating-point arithmetic.
It uses one table look-up, one division by a variable, and one remainder operation with a constant (which a compiler can optimize to a multiplication and some shifts and adds).
(Note that position is adjusted in the table lookup to be one-based to match the code in the question, but common practice would be to call the units position position 0 instead of position 1.)
If digits are to be extracted for multiple positions or the whole number, then other implementations should be considered.
You said that you extract a digit in order to display the game score; so I assume you will use the whole original number.
You can extract all the digits in a loop this way:
int number = 1234; // this variable will be consumed
while (number) {
rightmostdigit = number % 10;
// do something with the extracted digit
number /= 10; // discard the rightmost at go to the next
}
The above routine extracts digits from the right, so the score shall be drawn from right to left. Warning that if the number is zero, the loop is never executed...
If you want to extract from left, and supposing a fixed-length score (like "00123"), you can store the single digits in an array, then read them back in the inverse direction: it should be faster than trying to extract the digits from left to right.
I came across this program to convert decimals numbers into their binary equivalent in C. I do not understand how the printf statement works in this program.
int main()
{
int N;
scanf("%d", &N); // Enter decimal equivalent here
for( int j = floor(log2(N)); j >= 0; j-- ){
printf("%d", (N >> j) & 1);
}
}
Let's take an example to get through this problem. Suppose you enter N=65. Its binary representation is - 1000001. When your given code goes through it, j will start at floor(log2(65)), which is 6. So, the given loop will run 7 times, which means 7 numbers will be printed out (which fits the fact that 65's binary representation has 7 digits).
Inside the loop - The number is shifted by j bits each time to the right. When 1000001 is shifted to the right by 6 bits, it becomes 0000001. If shifted by 5, it is 0000010, and so on. It goes down to a shift by 0 bits which is the original number. When each of these shifted numbers are &ed with 1, only the least significant bit (the right most bit) remains. And this digit can either be a 0 or a 1.
If you would have noticed each right shift divides the number by 2. So when 1000001 is shifted by 1 to make 0100000, it is the binary representation of 32, which indeed is 65/2 in C. After all, this is the way someone manually calculates the binary representation of a number. Each division by 2 gives you a digit (starting from the end) of the representation, and that digit is either a 0 or a 1. The & helps in getting the 0 or 1.
In the end, 65 becomes 1000001.
What it is doing is:
Finding the largest number j such that 2^j <= N
Starting at the jth bit (counting from the right) and moving to the right ...
chopping off all of the bits to the right of the current chosen bit
chopping off all of the bits to the left of current chosen bit
printing the value of the single remaining bit
The code actually has undefined behavior because you did not include <stdio.h>, nor <math.h>. Without a proper declaration of floor() and log2(), the compiler infers the prototype from the calling context and gets int log2(int) and int floor(int), which is incompatible with the actual definition in the C library.
With the proper includes, log2(N) gives the logarithm of N in base 2. Its integral part is the power of 2 <= N, hence 1 less than the number of bits in N.
Note however that this method does not work for negative values of N and only works by coincidence for 0 as the conversion of NaN to int gives 0, hence a single binary digit.
I was trying to count the number of consecutive bits of a bit-stream and I have this code. I assume that, this has to to run until when the number becomes 0 and the count then should return the value. But why is there no conditional statement to equate the number to zero(otherwise i doubt this can be an infinite loop) so that the execution jumps out of the loop and returns the count value once it's over. Please don't duplicate it as I'm only a kid without adequate reputation to comment any doubt.
int count_consecutive_ones(int in) {
int count = 0;
while (in)
{
in = (in & (in << 1));
count++;
}
return count;
}
First of all: The code does not count the number of consecutive bits of a bitstream. All bits in a bitstream are consecutive. That's way it is called a bit stream. It counts the number of consecutive ones in a bitstream. No, not in a bitstream, but in an integer.
Let me explain that:
while(in)
{
…
}
… is a while loop that runs as long as its condition is true. In C for a long time there has been no boolean type at all. A condition is false if the expression of any type is not a representation of zero, otherwise true. For integers that means, that the value of 0 is false, each other value is true. You can read that as …
while( in != 0)
{
…
}
… with != in the meaning of unequal.
Inside the loop you have …:
in = (in & (in << 1));
This is a bit tricky: It moves the integer by one bit to the left (in << 1) and then computes the bit-and operation with the original value itself. This produces 1's on all places, where a 1 is aside a 1. Doing that over and over, it counts 1's being aside.
So you do not have to iterate over the bits to find a leading 1 and then the number of 1's following.
I am looking at the following piece of code:
void printd(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n / 10)
printd(n / 10);
putchar(n % 10 + '0');
}
I understand the first if statement fine, but the second one has me confused on a couple of points.
By itself, since "n" is an integer, I understand that n/10 will shift the decimal point to the left once - effectively removing the last digit of the number; however, I am having a little trouble understanding how this can be a condition by itself without the result being equal to something. Why isn't the condition if ((n/10) >= 0) or something?
Also, why is the '0' passed into the putchar() call?
Can someone tell me how it would read if you were to read it aloud in English?
Thanks!
The n / 10 will evaluate to false if the result is 0, true otherwise. Essentially it's checking if n > 10 && n < -10 (the -10 doesn't come into play here due to the n = -n code)
The + '0' is for character offset, as characters '0'-'9' are not represented by numbers 0-9, but rather at an offset (48-57 with ascii).
Can someone tell me how it would read if you were to read it aloud in English?
If you're talking about the conditional, then I would say "if integer n divided by 10 is not zero"
n/10 will not shift the decimal number since n is an integer. The division will produce the result like this: if n = 25, then n/10 would be 2 (without any decimal points), similarly if n = 9, then n/10 would be 0 in which case if condition would not be satisfied.
Regarding the +'0', since n%10 produces an integer result and in putchar you are printing a char , you need to convert the integer to a char. This is done by adding the ascii value of 0 to the integer.
In C, there is no separate boolean type; an expression like a > b evaluates to zero if false, non-zero if true. Sometimes you can take advantage of this when testing for zero or non-zero in an int.
As for the '0', that just performs character arithmetic so that the right character is printed. The zero character has an ASCII encoding value which isn't zero, so the n value is used as an offset from that encoding to get the right numeric digit printed out.
For instance n = 8135267 => 16
Here is a solution but I don't understand it.
int sumOddDigits(int n) {
if(n == 0)
return 0;
if(n%2 == 1) //if n is odd
//returns last digit of n + sumOddDigits(n/10) => n/10 removes the last digit of n
return n % 10 + sumOddDigits(n/10)
else
return sumOddDigits(n/10);
}
Integer divison by ten "cuts off" the last digit: I.e. 1234/10 results in 123.
Modulo 10 returns the last digit: i.e. 1234%10 results in 4.
Thus, the above code considers always the last digit. If the last digit is odd (hence the %2==1 stuff) it will be counted, otherwise not. So, if it should count the digit, it takes the last digit (the % 10-stuff) and continues computing with the remaining digits (the recursion with the /10-stuff) and adding them to the digit. If the current digit shall not be counted, it continues just with the remaining digits (thus the recursion and the /10-stuff) without adding it to the current digit.
If the argument is 0, this means that the whole number is traversed, thus the function terminates with returning 0.
% is the modulo operator. It basically finds the remainder of dividing by a number.
n %2 n is only 1 if it's odd. % 10 gets the remainder of the dividing the number by 10, this gets you the currently last digit. Integer division by 10 gets you the next digit as the current last digit (1567/10 = 156)
Think about it this way: Starting with your known answer of 8135267 => 16, if I asked you for the sum of the odd digits in *3*8135267, what would you do? What if I asked for *4*8135267? How do your manual steps related to that function?
Think of it this way. If you get an even digit your function returns it + function value of the number without that digit. Otherwise it returns the function value of the number without the last digit. On your example:
813526(7) -> 0 + sumEvenDigits(813526)
6 + sumEvenDigits(81352)
2 + sumEvenDigits(8135)
....
8 + sumEvenDigits(0)
0 = 16
Hope this helps.
int sum_odd_digits(int n)
{
int s=0,r=0;
if(n==0)
return 0;
r = n%10;
if(r%2==1)
s = s+r;
n=n/10;
return s+ sum_odd_digits(n);
}