Write a program using bitwise operators to determine positive remaindar - c++

Write a program that reads an integer value from the keyboard into a variable of type int, and uses one of the bitwise operators (i.e. not the % operator!) to determine the positive remainder when divided by 8.
For example, 29 = (3x8)+5 and 14 = ( 2x8)+2 have positive remainder 5 and 2, respectively, when divided by 8.
I tried to search how can I solve it. What I did is to break given examples numbers into binary.
29 => 101001
8 => 001000
5 => 000101
I don't know what is operation I should do with 29 and 8 to get result 5 in binary.
While searching there's some guys said that we should do (& operation with 7 )
remainder = remainder & 7 ;
Then I tried to do this with Value itself
value = value & 7 ;
and Here's my code After doing it ...
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int value = 0;
int divisor = 8;
int remainder = 0;
cout << "Enter an integr and I'll divide it by 8 and give you the remainder!"
<<endl;
cin >> value;
value = value & 7;
remainder = value & divisor;
cout << remainder;
return 0;
}
It gave me result 0 when I use value 29. I don't know what I wrote was right or not.

Simply & the number itself with 7. Also, 29 = 0b11101. To generalise, the remainder when divided by a number 2 ^ n is found by &ing it with (2 ^ n) - 1 (^ == power of)
Thus, to obtain remainder modulo 16, & with 15, and so on.

Since 8 is exactly 2^3, the modulo-8 remainder of any number is composed of its last three binary digits, i. e. it equals the number bitwise-and 7:
unsigned rem8 = number & 7;
(7 is 111 in binary, that's why.)

Related

Have some doubts in the operation [Bitwise Manipulation]

#include <iostream>
#include <math.h>
using namespace std;
// converting from decimal to binary
int main()
{
int n, bit, ans = 0, i = 0;
cout << "enter a number: ";
cin >> n;
while (n > 0)
{
bit = n & 1;
ans = round(bit * pow(10, i)) + ans; /* we used 'round' bcoz pow(10, 2) give 99.99999
it differs from compiler to compiler */
n = n >> 1;
i++;
}
cout << ans;
return 0;
}
I am unable to understand that in while(n>0), n will be stored as binary form or decimal form.
That is if n=5, so whether while loop check for (5>0) or (101>0).
Can anyone explain what is happening here?
I am new to this platform, please don't delete my question. My earlier questions are also gets deleted due enough dislikes. I am here to learn and am still learning.
"Decimal" and "Binary" are text representations of a value. n is an int, not text, so it holds the value 5. If I have 5 apples on a desk, then there is no "decimal" or "binary" involved. THere's just 5 apples. Same with int.
cin >> n;
while (n > 0)
This loop continues because 5 > 0.
n = n >> 1;
This is just a fancy way of writing n = n / 2, so then n becomes 2. Since 2 > 0, the loop continues. On the third run, n becomes 1, and since 1 > 0, the loop continues a third time. On the fourth run, n becomes 0, and 0 == 0, so the while loop exits.
Both n and ans are integers that your computer stores in a binary format. If n = 5 then n is both 5 and 0b0101. Your loop converts one integer n into a second integer ans which only uses the digits 1 and 0 and looks like the integer n in binary.
It does this by converting each power of two in n into a power of ten and adding it into ans. The integer 5 will become the integer 101 (one hundred and one).
In the loop, when you use the bitwise operator >> you are manipulating the underlying binary representation of the number directly, in this case, shifting all of the bits in the integer to the right and feeding in zeros on the left to replace the bits that have moved.
So, if n is 5 then:
0b0101 >> 1 gives 0b0010, or 2
0b0101 >> 2 gives 0b0001, or 1
0b0101 >> 3 gives 0b0000, or 0
When you use the bitwise operator & (bitwise and) you are again operating directly on the binary representation. This time you are and-ing all of the bits in one number with the bit in another number. For example:
0b01100110 & 0b10101110 = 0b00100110
0b01100110 & 0b10011001 = 0b00000000
In your loop you are doing four things:
1. bit = n & 1
And-ing the integer n with one will mean that bit is equal to:
1 when there is a 1 in the 2^0 place (the least significant bit) and,
0 when there is not a 1 in the 2^0 place.
2. ans = round(bit * pow(10, i)) + ans
You take 10^i and multiply it by bit. So:
bit is zero this is zero
if bit is one this is some power of ten.
3. n = n >> 1
Shift one place to the right. The bit that was in the 2^1 place is now in the 2^0 place.
4. i++
Increment i which tracks both your current power of 2 and current power of ten.
#Mooing Duck has explained it incredibly well. I'd just add that you are being confused about the Number System
Decimal numbers are called the base 10 numbers (digits: 0 - 9, total: 10)
Binary numbers are called the base 2 numbers(digits/bits: 0 - 1, total: 2)
101 (base 10) is very different from 101 (base 2)
When we use bitwise operators such as (<<, >>, &, ^, |) we manipulate the bits of the decimal (hence the name bitwise operators)
So, when you are doing 5 >> 1 you are actually doing 101 (base 2) >> 1 which results in 010 (base 2)
When you keep shifting the bits to the right(equivalent to dividing by 2), at one point you'll be left with no 1s and only 0s. And what's 0 (base 2)? Its 0(base 10). Hence, the loop breaks.

Program to compute n-th number that doesn't contain given digit

I'm being requested to write a C++ program that computes the n-th number that doesn't contain a given digit and the time execution to be lower than 0.1 seconds. Memory doesn't seem to be an issue, as I'm allowed the use of up to 64 MB.
The original text of the problem goes like this:
Cifra4
To represent numbers, it was decided not to use the digit C
again.
Thus, from the array of natural numbers, all numbers containing the
digit C will be erased. Let the new array be S.
Requirements
1) Determine the N-th number in S.
2) Y and Z are two natural
numbers from the array of all natural numbers. Determine the number of
natural numbers removed from Y to Z.
Input data
The input file cifra4.in contains the first number T representing the
type of requirement. If T == 1, the second row will contain
the digit C and the number N. If T == 2, the
second line will contain the digit C and two natural numbers Yand
Z.
Output data
In the output file cifra4.out will contain in the first row
one natural number according to the type of requirement.
Restrictions and clarifications
1 ≤ N ≤ 10 ^ 13
0 ≤ C ≤ 9
1 ≤ Y ≤ 10 ^ 13
1 ≤ Z ≤ 10 ^ 13
for 20% of the tests, N will have a maximum of 5 digits
for 20% of the tests, Y and Z will have a maximum of 6 digits
Example 1
cifra4.in
1
0 11
cifra4.out
12
Example 2
cifra4.in
2
1 3 20
cifra4.out
10
My best try was a code that determined (or at least was supposed to) the n-th number that doesn't contain the digit "0", but for 10 ^ 13 it returned 23210987654321, which obviously contains 0.
My slower, but correct approach was what I ended up keeping. Here is the code:
#include <fstream>
std::ifstream in("cifra4.in");
std::ofstream out("cifra4.out");
const long long pow_of_10[14] = {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
10000000000, 100000000000, 1000000000000};
void req_1 ()
{
short digit;
long long n;
in >> digit >> n;
for (long long i = 0; i <= n; i++)
{
long long nr = i;
if (nr)
{
long k = 1;
do
{
if (nr % 10 == digit)
{
n += pow_of_10[k];
i += pow_of_10[k] - 1;
break;
}
nr /= 10;
k++;
}
while (nr);
}
else if (digit == 0) n++;
}
out << n - 1;
}
void req_2()
{
short digit;
long long lhs, rhs;
long long elim = 0;
in >> digit >> lhs >> rhs;
for (long long i = lhs; i <= rhs; i++)
{
long long nr = i;
while (nr)
{
if (nr % 10 == digit)
{
elim++;
break;
}
nr /= 10;
}
}
out << elim;
}
int main()
{
short requirement;
in >> requirement;
if (requirement == 1)
req_1();
else
req_2();
}
NOTE
I'm not asking for code necesarily, but for ideas, possible algorithms that can execute up to 10 ^ 13 in decent time, preferably the time requested by the problem, but 1 second will do fine for me.
Imagine that 9 is the forbidden digit. In this case you can just convert your number to base-9 and you're done.
Now, what happens when the forbidden digit is different, say d? It's still a base-9 number but you have to map your digits, such that digits below d remain unaffected, and d and above are mapped to the digit d + 1.
For example, when the forbidden digit is 7 and n is 125.
Step 1: convert to base-9: 12510 = 1489
Step 2: map the digits. 1 → 1, 4 → 4, 8 → 9
The solution is 149.
Since the decimal digits of a number are "independent" of each other, in that setting one digit does not affect any other digits - once you've fixed a prefix of (at least one) more-significant digits, leaving n' less-significant digits, you know you have exactly (10 - 1)^n' = 9^n' numbers with that prefix and no forbidden digits in the unfixed part. For example, for 3-digit numbers beginning with 1, there are exactaly 81 numbers with no 0 in them.
The only 'snag' here is that setting the most-significant digit to zero means that you get the same number for different numbers of digits (012, 0012 etc.). But you should be able to work around this issue as well - by determining how many digits you're going to need for the n'th number without your forbidden digit. Very similar to the argument I described above. Then you know you have 10-1 = 9 options there if your forbidden digit is 0 or 10-2 = 8 otherwise.

Code for converting binary number to decimal number

I have some code that I wrote up that will successfully return me a binary number. For example, running the code below with an input of 101 will return 5. However, the problem arises when I add 0 bits to the left of MSB, thus not changing the value. When I input 0101 into the system, I should expect 5 to be returned again, but it returns 17 instead.
Here is my code:
int dec1 = 0, rem1=0, num1, base1 = 1;
int a = 101;
while (a > 0){
rem1 = a % 10;
dec1 = dec1 + (rem1 * base1);
base1 = base1 * 2;
a = a / 10;
}
cout << dec1 << endl;
The output of this is 5. Correct.
However, when 'a' is changed to 0101, the output becomes 17. I believe my error has to do with a misunderstanding of the modulo operator.
101%10 = 1 right? Does the compiler typically read 0101%10 the same way?
I added a cout statement to my code to see what value is stored in rem1 after the value of 0101%10 is calculated.
int dec1 = 0, rem1=0, num1, base1 = 1;
int a = 101;
while (a > 0){
rem1 = a % 10;
cout << rem1 << endl;
dec1 = dec1 + (rem1 * base1);
base1 = base1 * 2;
a = a / 10;
}
cout << dec1 << endl;
From this, I was able to see that right after 0101%10 is calculated, a value of 5 is stored in rem1, instead of 1.
Does adding this 0 in front of the MSB tell the compiler "hey, this number is in binary?" because if the compiler is reading 5%10 instead of 0101%10, then I guess the error makes sense.
Upon testing my theory, I changed 'a' to 1000 and the output was 8, which is correct.
Changing 'a' to 01000 gives a result of 24. rem1= 01000%10 should be 0, however rem1 is storing 2. 01000 binary = 8 decimal. 8%10=8? not 2?
I'm an unsure of what is going on and any help is appreciated!
101 is parsed as a decimal (base 10) number, so you get your expected output.
0101 is parsed as an octal (base 8) number due to the leading zero. The leading zero here works just like the leading 0x prefix that denotes a hexadecimal (base 16) number, except that without the x it's base 8 instead of base 16.†
1018 = 82 + 80 = 64 + 1 = 65
65 % 10 = 5
65 / 10 = 6
6 % 10 = 7
5 * 2 + 7 = 17
If I were you, I'd add an assert(rem1 == 0 || rem1 == 1) inside your loop right after your assignment to rem1 as a sanity check. If you ever get a remainder larger than one or less than zero then there's obviously something wrong.
As rbaleksandar points out in his comment above, the easiest way to avoid this issue is probably to store your input as a c-string (char[]) rather than using an integer literal. This is also nice because you can just iterate over the characters to compute the value instead of doing % and / operations.
Alternatively, you could use hex literals (e.g., 0x101 or 0x0101) for all of your inputs, and change your math to use base 16 instead of base 10. This has the added advantage that base 10 division and remainder functions can be optimized by the compiler into much cheaper bit-shift and bit-mask operations since 16 is a power of 2. (E.g., 0x101 % 16 ==> 0x101 & 15, and 0x101 / 16 ==> 0x101 >> 4).
† For more info
see http://en.cppreference.com/w/cpp/language/integer_literal
0101 is Octal number, which value is 17.

What does "number>>1" mean in "binary(number >> 1)" (Decimal to Binary conversion)

This code converts decimal integer into binary. This is working perfectly. I know this has been done using recursion method...but I am not understanding how the parameter is working on the line 8 of this function. thanks in advance :) .
void binary(int number) {
int remainder;
if(number <= 1) {
cout << number;
return;
}
remainder = number%2;
binary(number >> 1);
cout << remainder;
}
In most "C inspired languages*", the operator >> represents the right (bitwise) shift operator. So the code
binary(number >> 1);
passes a value to the recursive call to binary(), which is shifted by one bit to the right (i.e. the same as integer division by 2).
The recursion stops when the number is <= 1, i.e. there are no more powers of 2 to divide the remaining number through by.
In the interim, the modulo 2 (% 2) remainder for the call is held over and written after the inner recursive call, so that it will retain the correct position in the power of 2.
e.g.
12 Decimal
/ 2 = 6 remainder 0 // printed fourth
/ 2 = 3 remainder 0 // printed third
/ 2 = 1 remainder 1 // printed second
> <= 1 so Print 1 // printed first
So 1100 will be printed.
* Wikipedias terminology

How to check for division by 7 for big number in C++?

I have to check, if given number is divisible by 7, which is usualy done just by doing something like n % 7 == 0, but the problem is, that given number can have up to 100000000, which doesn't fit even in long long.
Another constrain is, that I have only few kilobytes of memory available, so I can't use an array.
I'm expecting the number to be on stdin and output to be 1/0.
This is an example
34123461273648125348912534981264376128345812354821354127346821354982135418235489162345891724592183459321864592158
0
It should be possible to do using only about 7 integer variables and cin.get(). It should be also done using only standard libraries.
you can use a known rule about division by 7 that says:
group each 3 digits together starting from the right and start subtracting and adding them alternativly, the divisibility of the result by 7 is the same as the original number:
ex.:
testing 341234612736481253489125349812643761283458123548213541273468213
549821354182354891623458917245921834593218645921580
(580-921+645-218+593-834+921-245+917-458+623-891+354-182
+354-821+549-213+468-273+541-213+548-123+458-283+761-643
+812-349+125-489+253-481+736-612+234-341
= 1882 )
% 7 != 0 --> NOK!
there are other alternatives to this rule, all easy to implement.
Think about how you do division on paper. You look at the first digit or two, and write down the nearest multiple of seven, carry down the remainder, and so on. You can do that on any abritrary length number because you don't have to load the whole number into memory.
Most of the divisibility by seven rules work on a digit level, so you should have no problem applying them on your string.
You can compute the value of the number modulo 7.
That is, for each digit d and value n so far compute n = (10 * n + d) % 7.
This has the advantage of working independently of the divisor 7 or the base 10.
You can compute the value of the number modulo 7.
That is, for each digit d and value n so far compute n = (10 * n + d) % 7.
This has the advantage of working independently of the divisor 7 or the base 10.
I solved this problem exactly the same way on one of programming contests. Here is the fragment of code you need:
int sum = 0;
while (true) {
char ch;
cin>>ch;
if (ch<'0' || ch>'9') break; // Reached the end of stdin
sum = sum*10; // The previous sum we had must be multiplied
sum += (int) ch;
sum -= (int) '0'; // Remove the code to get the value of the digit
sum %= 7;
}
if (sum==0) cout<<"1";
else cout<<"0";
This code is working thanks to simple rules of modular arithmetics. It also works not just for 7, but for any divisor actually.
I'd start by subtracting some big number which is divisible by 7.
Examples of numbers which are divisible by 7 include 700, 7000, 70000, 140000000, 42000000000, etc.
In the particular example you gave, try subtracting 280000000000(some number of zeros)0000.
Even easier to implement, repeatedly subtract the largest possible number like 70000000000(some number of zeros)0000.
Because I recently did work dealing with breaking up numbers, I will hint that to get specific numbers - which is what you will need with some of the other answers - think about integer division and using the modulus to get digits out of it.
If you had a smaller number, say 123, how would you get the 1, the 2, and the 3 out of it? Especially since you're working in base 10...
N = abc
There is a simple algorithm to verify if a three-digit number is a multiple of 7:
Substitute a by x and add it to bc, being x the tens of a two-digit number multiple of 7 whose hundreds is a.
N = 154; x = 2; 2 + 54 = 56; 7|56 and 7|154
N = 931; x = 4; 4 + 31 = 35; 7|35 and 7|931
N = 665; x = 5; 5 + 65 = 70; 7|70 and 7|665
N = 341; x = 6; 6 + 41 = 47; 7ł47 and 7ł341
If N is formed by various periods the inverse additive of the result of one period must be added to the sum of the next period, this way:
N = 341.234
6 + 41 = 47; - 41 mod 7 ≡ 1; 1 + 4 + 34 = 39; 7ł39 and 7łN
N = 341.234.612.736.481
The result for 341.234 is 39. Continuing from this result we have:
-39 mod 7 ≡ 3; 3 + 5 + 6 + 1 + 2 + 1 = 18; - 18 mod 7 ≡ 3; 3 + 0 + 36 = 39; - 39 mod 7 ≡ 3;
3 + 1 + 81 = 85; 7ł85 and 7łN
This rule may be applied entirely through mental calculation and is very quick.
It was derived from another rule that I created in 2.005. It works for numbers of any magnitude and for divisibility by 13.
At first Take That Big Number in string And then sum every digit of string. at last check if(sum%7==0)
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int n,i,j,sum,k;
sum=0;
string s;
cin>>s;
for(i=0;i<s.length();i++)
{
sum=sum+(s[i]-'0');
}
if(sum%7==0)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
return 0;
}