wrote function to calculate set bits from 0 to n, - c++

in this function i check if the no. is one less than the power of 2 and then make recursive calls for 2^b - 1 and n - 2^b(this call keeps happening till the no. here is one less than a power of 2)
now I know the code is wrong but why does it give segmentation fault.
int countSetBits(int n)
{
if (n == 0)
return 0;
int b = floor(log2(n));
if ( (n + 1) & n == 0 ) {
return (1<<b)* floor(log2(n + 1));
}
return (n - 1<<b + 1) + countSetBits(n - 1<<b) + countSetBits(1<<b - 1);
}

The infinite number of (recursive) function calls causes stack overflow. The program's stack has become too large and tries to "overflow" into the next memory segment. This is not allowed, and hence the segfault.

The reasons for the errors are two-fold:
You are using floating point numbers, in floor and log2. Those are imprecise and won't give you the exactness you need for this task.
You are left shifting your numbers (making them bigger). I didn't follow the logic you wanted, but usually, the approach is to take the least bits out and then right-shift the numbers (>>)
Lastly, either use a debugger, or introduce debug couts to see what your program is doing, that will make it overall much easier.

Related

Music Chairs problem implementation in C++

I am currently practicing algorithms and DS. I have stumbled upon a question that I can't figure out how to solve. So the question's link is there:
In summary, it says that there is a number of chairs in a circle, and the position of the person (relative to a certain chair), and how many M movements he should make.
So the input is as following:
3 integer numbers N, M, X , The number of chairs, the number of times the boy should move and the first chair he will start from respectively ( 1  ≤  X  ≤  N < 2^63 , 0  ≤  M < 2^63 )
So, what have I done so far? I thought about the following:
So I thought that the relative position after M movements is (x+m) % n, and since this can cause Integer overflow, I have done it like that, ((x%n) + (m%n)) % n. I have figured out that if the person has reached the last index of chair, it will be 0 so I handled that. However, it passes only 2 tests. I don't need any code to be written, I want to directed in the right way of thinking. Here is my code so far:
#include <iostream>
using namespace std;
int main() {
long long n, m, x;
cin >> n >> m >> x;
// After each move, he reaches (X+1).
// X, N chairs.
// ((X % N) + (M % N)) % N;
// Odd conideration.
if ( m % 2 == 1) {
m += 1;
}
long long position = (x % n + m % n) % n;
if (position == 0) {
position = n;
}
cout << position;
return 0;
}
If the question required specific error handling, it should have stated so (so don't feel bad).
In every real-world project, there should be a standard to dictate what to do with weird input. Do you throw? Do you output a warning? If so, does it have to be translated to the system language?
In the absence of such instructions I would err toward excluding these values after reading them. Print an error to std::cerr (or throw an exception). Do this as close to where you read them as possible.
For overflow detection, you can use the methods described here. Some may disagree, and for a lab-exercise, it's probably not important. However, there is a saying in computing "Garbage in == Garbage out". It's a good habit to check for garbage before processing, rather than attempting to "recycle" garbage as you process.
Here's the problem:
Say the value of N is 2^63-1, and X and M are both 2^63 - 2.
When your program runs untill the ((X % N) + (M % N)) % N part,
X % N evaluates into 2^63 - 2 (not changed), and so does M % N.
Then, the addition between the two results occurs, 2^63 - 2 + 2^63 - 2 there is the overflow happening.
After the comment of #WBuck, the answer is actually rather easy which is to change the long long to unsigned because there are no negative numbers and therefore, increase the MAX VALUE of long long (when using unsigned).
Thank you so much.

Recursion with C++

I am learning recursion in my current class and the idea is a little tricky for me. From my understanding, when we build a function it will run as many times until our "base case" is satisfied. What I am wondering is how this looks and is returned on the stack. For an example I wrote the following function for a simple program to count how many times a digit shows up in an integer.
What does this look and work in a stack frame view? I don't completely understand how the returning works. I appreciate the help!
int count_digits(int n, int digit) {
// Base case: When n is a single digit.
if (n / 10 == 0) {
// Check if n is the same as the digit.
// When recursion hits the base case it will end the recursion.
if (n == digit) {
return 1;
} else {
return 0;
}
} else {
if (n % 10 == digit) {
return (1 + count_digits(n / 10, digit));
} else {
return (count_digits(n / 10, digit));
}
}
}
What does this look and work in a stack frame view? I don't completely understand how the returning works. I appreciate the help!
Let's try to build the solution bottom-up.
If you called the function - int count_digits(int n, int digit) as count_digits(4, 4) what would happen ?
This is the base case of your solution so it is very easy to see what is the return value. Your function would return 1.
Now, let's add one more digit and call the function like- count_digits(42, 4). What would happen ?
Your function will check the last digit which is 2 and compare with 4 since they are not equal so it will call the function count_digits(4, 4) and whatever is the returned value, will be returned as the result of count_digits(42, 4).
Now, let's add one more digit and call the function like - count_digits(424, 4). What would happen ?
Your function will check the last digit which is 4 and compare with 4 since they are equal so it will call the function count_digits(42, 4) and whatever is the returned value, will be returned by adding 1 to it. Since, number of 4s in 424 is 1 + number of 4s in 42. The result of count_digits(42,4) will be calculated exactly like it was done previously.
The recursive function builds up the solution in a top-down manner. If there are n digits initially, then your answer is (0 or 1 depending on the last digit) + answer with n-1 digits. And this process repeats recursively. So, your recursive code, reduces the problems by one digit at a time and it depends on the result of the immediate sub-problem.
You can use the C++ tutor at pythontutor.com website for step by step visualization of the stack frame. http://pythontutor.com/cpp.html#mode=edit
You can also try with smaller inputs and add some debug output to help you track and see how recursion works.
Check this stackoverflow answer for understanding what a stack frame is - Explain the concept of a stack frame in a nutshell
Check this stackoverflow answer for understanding recursion -
Understanding recursion
If you would like more help, please let me know in comments.

Prevent a user from entering a value which would cause integer to overflow

I'm very new to C++ programming, and have written a simple program to calculate the factorial of an integer provided by the user. I am attempting to account for inputs which would cause an error, or do not make sense (e.g. I have accounted for input of a negative number/-1 already). I want to print out an error if the user enters a number whose factorial would be larger than the maximum integer size.
I started with:
if(factorial(n) > INT_MAX)
std::cout << "nope";
continue
I tested this with n = ~25 or 26 but it doesn't prevent the result from overflowing and printing out a large negative number instead.
Second, I tried assigning this to a variable using a function from the 'limits.h' header and then comparing the result of factorial(n) against this. Still no luck (you can see this solution in the code sample below).
I could of course assign the result to a long and test against that but you wouldn't have to go very far until you started to wrap around that value, either. I'd prefer to find a way to simply prevent the value from being printed if this happens.
#include <iostream>
#include <cstdlib>
#include <limits>
int factorial(int n)
{
auto total = 1;
for(auto i = 1; i <= n; i++)
{
total = total * i; //Product of all numbers up to n
}
return total;
}
int main()
{
auto input_toggle = true;
auto n = 0;
auto int_max_size = std::numeric_limits<int>::max();
while(input_toggle = true)
{
/* get user input, check it is an integer */
if (factorial(n) > int_max_size)
{
std::cout << "Error - Sorry, factorial of " << n << " is larger than \nthe maximum integer size supported by this system. " << std::endl;
continue;
}
/* else std::cout << factorial(n) << std::endl; */`
As with my other condition(s), I expect it to simply print out that small error message and then continue asking the user for input to calculate. The code does work, it just continues to print values that have wrapped around if I request the factorial of a value >25 or so. I feel this kind of error-checking will be quite useful.
Thanks!
You are trying to do things backwards.
First, no integer can actually be bigger than INT_MAX, by definition - this is a maximum value integer can be! So your condition factorial(n) > int_max_size is always going to be false.
Moreover, there is a logical flaw in your approach. You calculate the value first and than check if it is less than maximum value allowed. By that time it is too late! You have already calculated the value and went through any overflows you might have encountered. Any check you might be performing should be performed while you are still doing your calculations.
In essence, you need to check if multiplying X by Z will be within allowed range without actually doing the multiplication (unfortunately, C++ is very strict in leaving signed integer overflow undefined behavior, so you can't try and see.).
So how do you check if X * Y will be lesser than Z? One approach would be to divide Z by Y before engaging in calculation. If you end up with the number which is lesser than X, you know that multiplying X by Y will result in overflow.
I believe, you know have enough information to code the solution yourself.

Having trouble understanding a portion of code (bit operation)

I can't understand how to count number of 1's in binary representation.
I have my code, and I hope someone can explain it for me.
Code:
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
Why while ? For example if i have 1011, it wouldn't stop at 0?
Why nr += x%2 ?
Why x/=2 ?!
First:
nr += x % 2;
Imagine x in binary:
...1001101
The Modulo operator returns the remainder from a / b.
Now the last bit of x is either a 0, in which case 2 will always go into x with 0 remainder, or a 1, in which case it returns a 1.
As you can see x % 2 will return (if the last bit is a one) a one, thus incrementing nr by one, or not, in which case nr is unchanged.
x /= 2;
This divides x by two, and because it is a integer, drops the remainder. What this means is is the binary was
....10
It will find out how many times 2 would go into it, in this case 1. It effectively drops the last digit of the binary number because in base 2 (binary) the number of times 2 goes into a number is just the same as 'shifting' everything down a space (This is a poor explanation, please ask if you need elaboration). This effectively 'iterates' through the binary number, allowing the line about to check the next bit.
This will iterate until the binary is just 1 and then half that, drop the remainder and x will equal 0,
while (x != 0)
in which case exit the loop, you have checked every bit.
Also:
'count`is possibly not the most descriptive name for a function, consider naming it something more descriptive of its purpose.
nr will always be a integer greater or equal to zero, so you should probably have the return type unsigned int
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
This program basically gives the numbers of set bits in a given integer.
For instance, lets start with the example integer 11 ( binary representation - 1011).
First flow will enter the while loop and check for the number, if it is equal to zero.
while(11 != 0)
Since 11 is not equal to zero it enter the while loop and nr is assigned the value 1 (11%2 = 1).nr += 11%2;
Then it executes the second line inside the loop (x = x/2). This line of code assigns the value 5 (11/2 = 5 ) to x.
Once done with the body of the while loop, it then again checks if x ie 5 is equal to zero.
while( 5 != 0).
Since it is not the case,the flow goes inside the while loop for the second time and nr is assigned the value 2 ( 1+ 5%2).
After that the value of x is divided by 2 (x/2, 5/2 = 2 )and it assigns 2 to x.
Similarly in the next loop, while (2 != 0 ), nr adds (2 + 2%2), since 2%2 is 0, value of nr remains 2 and value of x is decreased to 1 (2/2) in the next line.
1 is not eqaul to 0 so it enters the while loop for the third time.
In the third execution of the while loop nr value is increased to 3 (2 + 1%2).
After that value of x is reduced to 0 ( x = 1/2 which is 0).
Since it fails the check (while x != 0), the flow comes out of the loop.
At the end the value of nr (Which is the number of bits set in a given integer) is returned to the calling function.
Best way to understand the flow of a program is executing the program through a debugger. I strongly suggest you to execute the program once through a debugger.It will help you to understand the flow completely.

Error in while loop?

I made a simple example for counting decimal points but it doesn't stop and doesn't give me the right answer here's my code:
double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
b*=10;
count++;
}
cout<<count;
the answer is supposed to be:
3
but instead the while loop keeps running Indefinitely .. what's wrong with my code?
You should have checked the INT_MAX first. The number would be different. It depends on whether you are running the code on a 32-bit or 64-bit machine. If it is way smaller than your initial b, you would definitely end up in the infinite loop. For example, the max of short integer type is 32767. In that case, the condition of your loop would be like this: 76327741.125 - some negative number, larger than 0. however, in the loop, you increased the value of b. The next time, when we hit the condition line, it would be something like this: 76327741.125*10 - some negative number
You should probably set b to be b - int(b), to make sure it doesn't keep increasing (and potentially overflowing).
double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
b = b - int(b); // Note the change here.
b*=10;
count++;
}
cout<<count;