Can someone please explain this bit manipulation code to me? - c++

I am new to competitive programming. I recently gave the Div 3 contest codeforces. Eventhough I solved the problem C, I really found this code from one of the top programmers really interesting. I have been trying to really understand his code, but it seems like I am too much of a beginner to understand it without someone else explaining it to me.
Here is the code.
void main(){
int S;
cin >> S;
int ans = 1e9;
for (int mask = 0; mask < 1 << 9; mask++) {
int sum = 0;
string num;
for (int i = 0; i < 9; i++)
if (mask >> i & 1) {
sum += i + 1;
num += char('0' + (i + 1));
}
if (sum != S)
continue;
ans = min(ans, stoi(num));
}
cout << ans << '\n';
}
The problem is to find the minimum number whose sum of digits is equal to given number S, such that every digit in the result is unique.
Eq. S = 20,
Ans = 389 (3+8+9 = 20)

Mask is 9-bits long, each bit represents a digit from 1-9. Thus it counts from 0 and stops at 512. Each value in that number corresponds to possible solution. Find every solution that sums to the proper value, and remember the smallest one of them.
For example, if mask is 235, in binary it is
011101011 // bit representation of 235
987654321 // corresponding digit
==> 124678 // number for this example: "digits" with a 1-bit above
// and with lowest digits to the left
There are a few observations:
you want the smallest digits in the most significant places in the result, so a 1 will always come before any larger digit.
there is no need for a zero in the answer; it doesn't affect the sum and only makes the result larger
This loop converts the bits into the corresponding digit, and applies that digit to the sum and to the "num" which is what it'll print for output.
for (int i = 0; i < 9; i++)
if (mask >> i & 1) { // check bit i in the mask
sum += i + 1; // numeric sum
num += char('0' + (i + 1)); // output as a string
}
(mask >> i) ensures the ith bit is now shifted to the first place, and then & 1 removes every bit except the first one. The result is either 0 or 1, and it's the value of the ith bit.
The num could have been accumulated in an int instead of a string (initialized to 0, then for each digit: multiply by 10, then add the digit), which is more efficient, but they didn't.

The way to understand what a snippet of code is doing is to A) understand what it does at a macro-level, which you have done and B) go through each line and understand what it does, then C) work your way backward and forward from what you know, gaining progress a bit at a time. Let me show you what I mean using your example.
Let's start by seeing, broadly (top-down) what the code is doing:
void main(){
// Set up some initial state
int S;
cin >> S;
int ans = 1e9;
// Create a mask, that's neat, we'll look at this later.
for (int mask = 0; mask < 1 << 9; mask++) {
// Loop state
int sum = 0;
string num;
// This loop seems to come up with candidate sums, somehow.
for (int i = 0; i < 9; i++)
if (mask >> i & 1) {
sum += i + 1;
num += char('0' + (i + 1));
}
// Stop if the sum we've found isn't the target
if (sum != S)
continue;
// Keep track of the smallest value we've seen so far
ans = min(ans, stoi(num));
}
// Print out the smallest value
cout << ans << '\n';
}
So, going from what we knew about the function at a macro level, we've found that there are really only two spots that are obscure, the two loops. (If anything outside of those are confusing to you, please clarify.)
So now let's try going bottom-up, line-by-line those loops.
// The number 9 appears often, it's probably meant to represent the digits 1-9
// The syntax 1 << 9 means 1 bitshifted 9 times.
// Each bitshift is a multiplication by 2.
// So this is equal to 1 * (2^9) or 512.
// Mask will be 9 bits long, and each combination of bits will be covered.
for (int mask = 0; mask < 1 << 9; mask++) {
// Here's that number 9 again.
// This time, we're looping from 0 to 8.
for (int i = 0; i < 9; i++) {
// The syntax mask >> i shifts mask down by i bits.
// This is like dividing mask by 2^i.
// The syntax & 1 means get just the lowest bit.
// Together, this returns true if mask's ith bit is 1, false if it's 0.
if (mask >> i & 1) {
// sum is the value of summing the digits together
// So the mask seems to be telling us which digits to use.
sum += i + 1;
// num is the string representation of the number whose sum we're finding.
// '0'+(i+1) is a way to convert numbers 1-9 into characters '1'-'9'.
num += char('0' + (i + 1));
}
}
}
Now we know what the code is doing, but it's hard to figure out. Now we have to meet in the middle - combine our overall understanding of what the code does with the low-level understanding of the specific lines of code.
We know that this code gives up after 9 digits. Why? Because there are only 9 unique non-zero values (1,2,3,4,5,6,7,8,9). The problem said they have to be unique.
Where's zero? Zero doesn't contribute. A number like 209 will always be smaller than its counterpart without the zero, 92 or 29. So we just don't even look at zero.
We also know that this code doesn't care about order. If digit 2 is in the number, it's always before digit 5. In other words, the code doesn't ever look at the number 52, only 25. Why? Because the smallest anagram number (numbers with the same digits in a different order) will always start with the smallest digit, then the second smallest, etc.
So, putting this all together:
void main(){
// Read in the target sum S
int S;
cin >> S;
// Set ans to be a value that's higher than anything possible
// Because the largest number with unique digits is 987654321.
int ans = 1e9;
// Go through each combination of digits, from 1 to 9.
for (int mask = 0; mask < 1 << 9; mask++) {
int sum = 0;
string num;
for (int i = 0; i < 9; i++)
// If this combination includes the digit i+1,
// Then add it to the sum, and append to the string representation.
if (mask >> i & 1) {
sum += i + 1;
num += char('0' + (i + 1));
}
// If this combination does not yield the right sum, try the next combination.
if (sum != S)
continue;
// If this combination does yield the right sum,
// see if it's smaller than our previous smallest.
ans = min(ans, stoi(num));
}
// Print the smallest combination we found.
cout << ans << '\n';
}
I hope this helps!

The for loop is iterating over all 9-digit binary numbers and turning those binary numbers into a string of decimal digits such that if nth binary digit is on then a n+1 digit is appended to the decimal number.
Generating the numbers this way ensures that the digits are unique and that zero never appears.
But as #Welbog mentions in comments this solution to the problem is way more complicated than it needs to be. The following will be an order of magnitude faster, and I think is clearer:
int smallest_number_with_unique_digits_summing_to_s(int s) {
int tens = 1;
int answer = 0;
for (int n = 9; n > 0 && s > 0; --n) {
if (s >= n) {
answer += n * tens;
tens *= 10;
s -= n;
}
}
return answer;
}

Just a quick way to on how code works.
First you need to know sum of which digits equal to S. Since each digit is unique, you can assign a bit to them in a binary number like this:
Bit number Digit
0 1
1 2
2 3
...
8 9
So you can check all numbers that are less than 1 << 9 (numbers with 9 bits corresponding 1 to 9) and check if sum of bits if equal to your sum based on their value. So for example if we assume S=17:
384 -> 1 1000 0000 -> bit 8 = digit 9 and bit 7 = digit 8 -> sum of digits = 8+9=17
Now that you know sum if correct, you can just create number based on digits you found.

Related

why for loop is not work correctly for a simple multiplication numbers 1 to 50?

code:
#include <iostream>
using namespace std;
int main() {
int answer = 1;
int i = 1;
for (; i <= 50; i++){
answer = answer * i;
}
cout << answer << endl;
return 0;
}
resault :
0
...Program finished with exit code 0
Press ENTER to exit console.
when i run this code in an online c++ compiler, it shows me zero(0) in console. why?
I will answer specifically the asked question "Why?" and not the one added in the comments "How?".
You get the result 0 because one of the intermediate values of answer is 0 and multiplying anything with it will stay 0.
Here are the intermediate values (I found them by moving your output into the loop.):
1
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
1932053504
1278945280
2004310016
2004189184
-288522240
-898433024
109641728
-2102132736
-1195114496
-522715136
862453760
-775946240
2076180480
-1853882368
1484783616
-1375731712
-1241513984
1409286144
738197504
-2147483648
-2147483648
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
E.g. here https://www.tutorialspoint.com/compile_cpp_online.php
Now to explain why one of them is 0 to begin with:
Because of the values, the sequence of faculties, quickly leaves the value range representable in the chosen data type (note that the number decimal digits does not increase at some point; though the binary digits are the relevant ones).
After that, the values are not really related to the correct values anymore, see them even jumping below zero and back...
... and one of them happens to be 0.
For the "How?" please see the comments (and maybe other, valuable answers).
Short Answer:
Your code is not working correctly because it performs 50 factorial, that the answer is 3.04*10^64. This number is greater than the int size, that is 2^31 - 1.
Long answer
You can check the problem logging the intermediate answers. This can help you to have some insights about the code situation. Here you can see that the number rotate from positive to negative, that's show the maximum possible multiplication with this code strategy.
https://onlinegdb.com/ycnNADKmX
The answer
30414093201713378043612608166064768844377641568960512000000000000
To archive the correct answer to any case of factorial, you need to have some strategy to operate to large numbers.
In fact, if you're working a large company, you probably have some library to work with large numbers. In this situation, is very important use this library to keep the code consistent.
In other hand, supposing that's an academic homework, you can choose any strategy in the Internet. In this situation I used the strategy that uses string to represent large numbers. You can see the solution here https://www.geeksforgeeks.org/multiply-large-numbers-represented-as-strings
The final program that compute the 50! in the proper manner using the string strategy to represent large numbers you can find here https://onlinegdb.com/XRL9akYKb
PS: I'll put the complete answer here to archive the code for future references.
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
//#see https://www.geeksforgeeks.org/multiply-large-numbers-represented-as-strings/
// Multiplies str1 and str2, and prints result.
string multiply(string num1, string num2)
{
int len1 = num1.size();
int len2 = num2.size();
if (len1 == 0 || len2 == 0)
return "0";
// will keep the result number in vector
// in reverse order
vector<int> result(len1 + len2, 0);
// Below two indexes are used to find positions
// in result.
int i_n1 = 0;
int i_n2 = 0;
// Go from right to left in num1
for (int i=len1-1; i>=0; i--)
{
int carry = 0;
int n1 = num1[i] - '0';
// To shift position to left after every
// multiplication of a digit in num2
i_n2 = 0;
// Go from right to left in num2
for (int j=len2-1; j>=0; j--)
{
// Take current digit of second number
int n2 = num2[j] - '0';
// Multiply with current digit of first number
// and add result to previously stored result
// at current position.
int sum = n1*n2 + result[i_n1 + i_n2] + carry;
// Carry for next iteration
carry = sum/10;
// Store result
result[i_n1 + i_n2] = sum % 10;
i_n2++;
}
// store carry in next cell
if (carry > 0)
result[i_n1 + i_n2] += carry;
// To shift position to left after every
// multiplication of a digit in num1.
i_n1++;
}
// ignore '0's from the right
int i = result.size() - 1;
while (i>=0 && result[i] == 0)
i--;
// If all were '0's - means either both or
// one of num1 or num2 were '0'
if (i == -1)
return "0";
// generate the result string
string s = "";
while (i >= 0)
s += std::to_string(result[i--]);
return s;
}
// Calculates the factorial of an inputed number
string fact(int in) {
string answer = "1";
for (int i = 2 ; i <= in; i++) {
string tmp = std::to_string(i);
answer = multiply(answer, tmp);
}
return answer;
}
int main()
{
string answer = fact(50);
cout << answer << endl;
return 0;
}

Add two octal numbers directly without converting to decimal

I'm trying to add two octal numbers by adding the corresponding digits but, I'm stuck when the case is that the sum of digits is greater than 7. I'll have to take a carry and add it to the next addition cycle. I'm unable to find the right expression to consider the carry and compute the final sum.
Another case to consider is when the octal numbers a and b do not have same number of digits, ex: 6 and 13 (6+13=21 in octal). I'm unable to establish a condition for the while loop for such a condition (if both have same number of digits I can run the while loop till either of them or both of them become zero)
Can somebody please help/complete the following code:
int octal_sum(int a,int b) //a and b and octal numbers
{
int sum=0,carry=0,d=0;
while(**???**)
{
d=0;
d=carry+(a%10)+(b%10);
a/=10;b/=10;
if(d>7)
{
carry=1;
d=d%8;
}
sum= **???**
}
return sum; //returns octal sum of a and b
}
Since you are passing ints, I assume that you are using decimal-coded octals*, i.e. decimal numbers that use only digits 0 through 7, inclusive. For example, number 1238 which is actually 8310 would be coded as 12310 using your scheme.
Deciding on the stopping condition - you want your while loop to continue until both numbers a, b, and carry turn zero. In other words, the condition should be a || b || carry
Adding the next digit to the sum - since the result is coded as decimal, you need to multiply digit d by the next consecutive power of ten. A simple way of doing that would be adding a new variable m which starts at 1 and gets multiplied by ten each iteration.
The result would look like this:
int octal_sum(int a,int b) {
int sum=0, carry=0, d=0, m = 1;
while(a || b || carry) {
d=0;
d=carry+(a%10)+(b%10);
a/=10;b/=10;
if(d>7) {
carry=1;
d=d%8;
} else {
carry = 0;
}
sum += d*m;
m *= 10;
}
return sum; //returns octal sum of a and b
}
Demo.
* This would be similar to Binary-Coded Decimal (BCD) representation, when a representation capable of storing hex digits is used to store decimal digits.
Here is the function I made. It is important to remember about the carry. Because if your numbers add up to be longer (ex: 7777 + 14 = 10013) if you ignore the carry, the code will only return four digits (your longest lenght of number), so 0013, which is 13. Not good. So we need to account for the carry. We must continue our loop until both our numbers and the carry are all 0.
Further more, if the digit you obtain by calculating a%10 + b%10 + carry is smaller than 8, then we no longer need to carry again, so we need to reset the value.
Note I'm using a digit rank integer, which basically allows me to add the digit to the beginning of the sum by multiplying by powers of ten and then adding it to the sum.
The final code looks like this.
int octal_sum(int a, int b)
{
int sum = 0, digit = 0, carry = 0, digit_rank = 1;
// Calculate the sum
while (a > 0 || b > 0 || carry)
{
// Calculate the digit
digit = a % 10 + b % 10 + carry;
// Determine if you should carry or not
if (digit > 7)
{
carry = 1;
digit %= 8;
}
else
carry = 0;
// Add the digit at the beggining of the sum
sum += digit * digit_rank;
digit_rank *= 10;
// Get rid of the digits of a and b we used
a /= 10;
b /= 10;
}
return sum;
}
Hope it helped you!
I am using StringBuilder to append character, which is better than using Strings, it's immutable.
2.read the char from String by converting String to char array, converting char to an integer by subtracting from its ASCII value '0'
make sure handle the carryforward case too
private static String OctaNumberAddition(String o1, String o2) {
StringBuilder sb = new StringBuilder();
int carry = 0;
for(int i = o1.length() - 1, j =o2.length()-1;i >= 0 || j >= 0;i--,j--){
int sum = carry + (i >= 0 ? o1.charAt(i) - '0':0)+(j >= 0 ? o2.charAt(j) - '0':0);
sb.insert(0,sum%8);
carry = sum /8;
}
if(carry > 0){
sb.insert(0,carry);
}
return sb.toString();
}

basic nestled loop calculate prime numbers between 1 - 239, inclusive

I am working on a program in which I must print out the number of primes, including 1 and 239, from 1 - 239 ( I know one and or two may not be prime numbers, but we will consider them as such for this program) It must be a pretty simple program because we have only gone over some basics. So far my code is as such, which seems like decent logical flow to me, but doesnt produce output.
#include <iostream>
using namespace std;
int main()
{
int x;
int n = 1;
int y = 1;
int i = 0;
while (n<=239)
{x = n % y;
if (x = 0)
i++;
if (y < n)
y++;
n++;
while (i == 2)
cout << n;
}
return 0;
}
The way I want this to work is to take n, as long as n is 239 or less, and preform modulus division with every number from 1 leading up to n. Every time a number y goes evenly into n, a counter will be increased by 1. if the counter is equal to 2, then the number is prime and we print it to the screen. Any help would be so greatly appreciated. Thanks
std::cout << std::to_string(2) << std::endl;
for (unsigned int i = 3; i<240; i += 2) {
unsigned int j = 3;
int sq = sqrt(i);
for (; j <= sq; j += 2) if (!(i%j)) break;
if (j>sq) std::cout << std::to_string(i) << std::endl;
}
first of all, the prime definition: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
so you can skip all the even numbers (and hence ... i+=2).
Moreover no point to try to divide for a number greater than sqrt(i), because then it will have a divisor less than sqrt(i) and the code finds that and move to the next number.
Considering only odd numbers, means that we can skip even numbers as divisors (hence ... j+=2).
In your code there are clearly beginner errors, like (x = 0) instead of x==0. but also the logic doesn't convince. I agree with #NathanOliver, you need to learn to use a debugger to find all the errors. For the rest, good luck with the studies.
lets start with common errors:
first you want to take input from user using cin
cin>>n; // write it before starting your while loop
then,
if (x = 0)
should be:
if (x == 0)
change your second while loop to:
while (i == 2){
cout << n;
i++;
}

Multiplying and comparing big numbers

I have this problem:
There are K lines of N numbers (32-bit). I have to choose the line with the max product of numbers.
The main problem is that N can go up to 20.
I'm trying to do this with logarithms:
ld sum = 0, max = 0;
int index = 0;
for(int i = 0; i < k; i ++) { // K lines
sum = 0, c = 0;
for(int j = 0; j < n; j ++) { // N numbers
cin >> t;
if(t < 0)
c++; // If the number is less than 0 i memorize it
if(t == 1 || t == -1) { // if numbers = 1 OR -1
sum += 0.00000001; // Because log(1) = 0
if(t == -1)
c ++;
}
else if(t == 0) { // if some number is equal to zero then the sum is = 0
sum = 0;
break;
}
else {
sum += log10(fabs(t));
}
}
if(c % 2 == 1) // if c is odd than multiply by -1
sum *= -1;
if(sum >= max) {
max = sum;
index = i;
}
if((sum - max) < eps) { // if sum is equal to max i'm also have to choose it
max = sum;
index = i;
}
}
cout << index + 1 << endl;
The program works in 50% of test cases. Is there a way to optimize my code?
In the case of t == -1, you increment c twice.
if you want to avoid bignum libs you can exploit that if you multiply b1 and b2 bits numbers then the result is b1+b2 bits long
so just sum the bit count of all multiplicants in a line together
and compare that
remember the results in some array
int bits(DWORD p) // count how many bits is p DWORD is 32bit unsigned int
{
DWORD m=0x80000000; int b=32;
for (;m;m>>=1,b--)
if (p>=m) break;
return b;
}
index sort the lines by the result bit count descending
if the first bitcount after sort is also the max then its line is the answer
if you have more than one max (more lines have the same bitcount and are the max also)
only then you have to multiply them together
Now the multiplication
you know should multiply all the max lines at once
each time all sub results are divisible by the same prime
divide them by it
this way the result will be truncated to much less bit count
so it should fit into 64 bit value
you should check out primes up to sqrt(max value)
when your max value is 32bit then check primes up to 65536
so you can make a static table of primes to check to speed thing up
also there is no point in checking primes bigger then your actual sub result
if you know how then this can be extremly speeded up by Sieves of Eratosthenes
but you will need to keep track of index offset after each division and use periodic sieve tables which is a bit complicated but doable
if you do not check all the primes but just few selected ones
then the result can still overflow
so you should handle that too (throw some error or something)
or divide all subresults by some value but that can invalidate the the result
Another multiplication approach
you can also sort the multiplicant by value
and check if some are present in all max lines
if yes then change them for one (or delete from lists)
this can be combined with the previous approach
bignum multiplication
you can make your own bignum multiplication
the result is max 20*32=640 bit
so the result will be array of unsigned ints (bit wide 8,16,32 ... whatever you like)
you can also handle the number as a string
look here for how to compute fast exact bignum square in C++
it contains also the multiplication approaches
and here NTT based Schönhage-Strassen multiplication in C++
but that will be slower for such small numbers like yours
at last you need to compare results
so compare from MSW do LSW and which ever line has bigger number in it is the max line
(MSW is most significant word, LSW is least significant word)
I think that this line is definitely wrong:
if(c % 2 == 1) // if c is odd than multiply by -1
sum *= -1;
If your product is in the range [0,1] then its logarithm will be negative and this will make it positive. I think you should keep it separate.

Multiplying two integers given in binary

I'm working on a program that will allow me to multiply/divide/add/subtract binary numbers together. In my program I'm making all integers be represented as vectors of digits.
I've managed to figure out how to do this with addition, however multiplication has got me stumbled and I was wondering if anyone could give me some advice on how to get the pseudo code as a guide for this program.
Thanks in advance!
EDIT: I'm trying to figure out how to create the algorithm for multiplication still to clear things up. Any help on how to figure this algorithm would be appreciated. I usually don't work with C++, so it takes me a bit longer to figure things out with it.
You could also consider the Booth's algorithm if you'd like to multiply:
Booth's multiplication algorithm
Long multiplication in pseudocode would look something like:
vector<digit> x;
vector<digit> y;
total = 0;
multiplier = 1;
for i = x->last -> x->first //start off with the least significant digit of x
total = total + i * y * multiplier
multiplier *= 10;
return total
you could try simulating a binary multiplier or any other circuit that is used in a CPU.
Just tried something, and this would work if you only multiply unsigned values in binary:
unsigned int multiply(unsigned int left, unsigned int right)
{
unsigned long long result = 0; //64 bit result
unsigned int R = right; //32 bit right input
unsigned int M = left; //32 bit left input
while (R > 0)
{
if (R & 1)
{// if Least significant bit exists
result += M; //add by shifted left
}
R >>= 1;
M <<= 1; //next bit
}
/*-- if you want to check for multiplication overflow: --
if ((result >> 32) != 0)
{//if has more than 32 bits
return -1; //multiplication overflow
}*/
return (unsigned int)result;
}
However, that's at the binary level of it... I just you have vector of digits as input
I made this algorithm that uses a binary addition function that I found on the web in combination with some code that first adjusts "shifts" the numbers before sending them to be added together.
It works with the logic that's in this video https://www.youtube.com/watch?v=umqLvHYeGiI
and this is the code:
#include <iostream>
#include <string>
using namespace std;
// This function adds two binary strings and return
// result as a third string
string addBinary(string a, string b)
{
string result = ""; // Initialize result
int s = 0; // Initialize digit sum
int flag =0;
// Traverse both strings starting from last
// characters
int i = a.size() - 1, j = b.size() - 1;
while (i >= 0 || j >= 0 || s == 1)
{
// Computing the sum of the digits from right to left
//x = (condition) ? (value_if_true) : (value_if_false);
//add the fire bit of each string to digit sum
s += ((i >= 0) ? a[i] - '0' : 0);
s += ((j >= 0) ? b[j] - '0' : 0);
// If current digit sum is 1 or 3, add 1 to result
//Other wise it will be written as a zero 2%2 + 0 = 0
//and it will be added to the heading of the string (to the left)
result = char(s % 2 + '0') + result;
// Compute carry
//Not using double so we get either 1 or 0 as a result
s /= 2;
// Move to next digits (more to the left)
i--; j--;
}
return result;
}
int main()
{
string a, b, result= "0"; //Multiplier, multiplicand, and result
string temp="0"; //Our buffer
int shifter = 0; //Shifting counter
puts("Enter you binary values");
cout << "Multiplicand = ";
cin >> a;
cout<<endl;
cout << "Multiplier = ";
cin >> b;
cout << endl;
//Set a pointer that looks at the multiplier from the bit on the most right
int j = b.size() - 1;
// Loop through the whole string and see if theres any 1's
while (j >= 0)
{
if (b[j] == '1')
{
//Reassigns the original value every loop to delete the old shifting
temp = a;
//We shift by adding zeros to the string of bits
//If it is not the first iteration it wont add any thing because we did not "shift" yet
temp.append(shifter, '0');
//Add the shifter buffer bits to the result variable
result = addBinary(result, temp);
}
//we shifted one place
++shifter;
//move to the next bit on the left
j--;
}
cout << "Result = " << result << endl;
return 0;
}