Restoring Division Implementation in C++ Using Bitwise Operators - c++

I'm trying to implement the restoring division algorithm, but I keep getting incorrect results. The trick is my assignment requires I implement +,-,*,/,% using only bitwise operators, loops, and branches. I've successfully implemented add(a,b), sub(a,b), and mul(a,b), hence their use in my div(a,b,&rem) method. Here's the code,
template<typename T>
T div(T dividend, T divisor, T &remainder){
unsigned q = 1;
unsigned n = mul(sizeof(T), CHAR_BIT);
remainder = dividend;
divisor <<= n;
for(int i=sub(n,1); i>=0; i=sub(i,1)) {
remainder = sub(remainder << 1, divisor);
if(remainder < 0) {
q &= ~(1 << i); // set i-th bit to 0
remainder = add(remainder, divisor);
} else {
q |= 1 << i; // set i-th bit to 1
}
}
return q;
}
I've tested all the edge cases and common examples for add, sub, and mul and I know they work correctly for any integer input.
It appears that for any input I get q = -1 and remainder = 0. I think the problem has something to do with the signing of T, or q and n. I think my implementation is the same, is there a reason why the method is returning -1 and 0?

You need to check the algorithm a bit closer. Your if(q < 0) comparison is using the wrong variable. It should be if (remainder < 0).

You mentioned this could have to do with signing of T, or q and n. You also mentioned in a comment that your implementation of T is a short.
Referring to the https://en.cppreference.com/w/cpp/language/types,
Your type T is always at least 16 bits but the intermediate values in shown div function are unsigned, or int, in general, which could be 32 bits depending on data model.
So your returned value is being truncated into the potentially smaller size of the T type holder to produce an expected result.

Related

How to write a loop that calculates power?

I'm trying to write a loop that calculates power without using the pow() function. I'm stuck on how to do that. Doing base *= base works for even powers upto 4, so there is something totally weird that I can't seem to figure out.
int Fast_Power(int base, int exp){
int i = 2;
int result;
if(exp == 0){
result = 1;
}
if(exp == 1){
result = base;
}
else{
for(i = 2; i < exp; i++){
base *= base;
result = base;
}
}
return result;
}
base *= base;
Your problem lies with that statement, you should not be changing base at all. Rather, you should be adjusting result based on the constant value of base.
To do powers, you need repeated multiplication, but the base *= base gives you a repeated squaring of the value and you'll therefore get a much bigger value than desired. This actually works for powers of four since you iterate 4 - 2 times, squaring each iteration, and x4 == (x2)2.
It will not work for higher powers like six since you iterate 6 - 2 times, and x6 != (((x2)2)2)2. That latter value is actually equivalent to x16.
As an aside (despite your contention), it's actually not guaranteed to work for powers of two. If you follow the code in that case, you'll see that result is never assigned a value so the return value will be arbitrary. If it's working for you, that's accidental and likely to bite you at some point.
The algorithm you can use should be something like:
float power(float base, int exponent):
# 0^0 is undefined.
if base == 0 and exponent == 0:
throw bad_input
# Handle negative exponents.
if exponent < 0:
return 1 / power(base, -exponent)
# Repeated multiplication to get power.
float result = 1
while exponent > 0:
# Use checks to detect overflow.
float oldResult = result
result *= base
if result / base is not close to oldResult:
throw overflow
exponent -= 1
return result
This algorithm handles:
negative integral exponents (since x-y = 1/xy);
the undefined case of 00; and
overflow if you do not have arbitrary-precision values (basically, if (x * y) / y != x, you can be reasonably certain an overflow has occurred). Note the use of "not close to", it's unwise to check floats for exact equality due to potential for errors due to precision limits - far better to implement a "is close enough to" check of some description.
One thing to keep in mind when translating to C or C++, a 2's complement implementation will cause issues when using the most negative integer, since its negation is often the same value again again due to the imbalance between the positive and negative values. This is likely to lead to infinite recursion.
You can fix that simply by detecting the case early on (before anything else), with something like:
if INT_MIN == -INT_MAX - 1 and exp == INT_MIN:
throw bad_input
The first part of that detects a 2's complement implementation, while the second detects the (problematic) use of INT_MIN as an exponent.
What you were doing wrong is base *= base each time through the loop, which changes the base itself, each iteration.
Instead you want the base to remain the same, and multiply the final result by that original base "exp" times.
int Fast_Power(int base, int exp){
int result=1;
if(exp == 0){
result = 1;
}
if(exp == 1){
result = base;
}
else{
for(int i = 0; i < exp; i++){
result *= base;
}
}
return result;
}
The basic but naive algorithm you are looking for that is horribly subject to integer overflow is:
int Fast_Power (int base, int exp)
{
int result = base;
if (exp == 0)
return result ? 1 : 0;
for (int i = 1; i < exp; i++) {
result *= base;
}
return result;
}
Note: result can very easily overflow. You need to employ some basic check to prevent integer-overflow and Undefined Behavior.
A minimal check (see: Catch and compute overflow during multiplication of two large integers), can be incorporated as follows. You must use a wider-type for the temporary calculation here and then compare the results against INT_MIN and INT_MAX (provided in the limits.h header) to determine if overflow occurred:
#include <limits.h>
...
int Fast_Power (int base, int exp)
{
int result = base;
if (exp == 0)
return result ? 1 : 0;
for (int i = 1; i < exp; i++) {
long long int tmp = (long long) result * base; /* tmp of wider type */
if (tmp < INT_MIN || INT_MAX < tmp) { /* check for overflow */
fputs ("error: overflow occurred.\n", stderr);
return 0;
}
result = tmp;
}
return result;
}
Now if you attempt, e.g. Fast_Power (2, 31); an error is generated and zero returned.
Additionally as #paxdiablo notes in the comment Zero to the power of zero may be undefined as there is no agreed upon value. You can add a test and issue a warning/error in that case if you desire.
First off, I agree it was probably a mistake to use base *= base. That said, it's not necessarily the mistake. My first impression was that OP was trying to compute powers the way that a human might do by hand. For example if you wanted to compute 3^13 a reasonable way is to start is by computing exponents which are powers of 2.
3^1 = 3
3^2 = 3*3 = 9
3^4 = 3^2 * 3^2 = 81
3^8 = 3^4 * 3^4 = 6,561
Then you can use these results to compute 3^13 as
3^13 = 3^1 * 3^4 * 3^8 = 1,594,323
Once you understand the steps you could code this. The hardest part is probably determining when to stop squaring the base, and which squares should be included in the final calculation. Perhaps surprisingly the (unsigned) binary representation of the exponent tells us this! This is because the digits in binary represent the powers of two which sum together to form the number. With that in mind we can write the following.
int Fast_Power(int base, int exp) {
int result = 1;
unsigned int expu = exp;
unsigned int power_of_two = 1;
while (expu > 0) {
if (power_of_two & expu) {
result *= base;
expu ^= power_of_two;
}
power_of_two <<= 1;
base *= base;
}
return result;
}
This code doesn't have overflow protection, though that would be a good idea. Sticking with the original prototype it still accepts negative exponents and returns integers, which is a contradiction. Since OP didn't specify what should occur upon overflow or negative exponents this code doesn't attempt to handle either of those cases. Reasonable methods of addressing these issues are provided by other answers.

How can I divide bitsets?

I use two bitsets to store two polynomials. I want one of them to be divided by 2nd and I want to get remainder after division. For example if I would like it on the paper:
w1= 110011010000000
w2 = 1111001
101000100
110011010000000 : 1111001
1111001
--1111110
1111001
----1110000
1111001
---100100 = remainder
Very few CPUs have builtin instructions for GF(2) division like this, so you'll need to implement it yourself with shifts and xors. Basically, you implement it exactly like you did it on paper -- shift the divisor up until its top bit matches that of dividend, then xor and shift back down, recording each position where you need an xor as a bit of the quotient. If all the polynomials in question fit in a single word, you can just use unsigned integer types for it. Otherwise, you'll need some multiprecision bitset type. The C++ std::bitset can be used for this, despite its problems (no easy way to convert between bitsets of different sizes, no bitscan functions).
template<size_t N> int top_bit_set(const bitset<N> &a) {
int i;
for (i = N-1; i >= 0; i--)
if (a.test(i)) break;
return i;
}
template<size_t N>
bitset<N> gf2_div(bitset<N> dividend, bitset<N> divisor, bitset<N> &remainder) {
bitset<N> quotient(0);
int divisor_size = top_bit_set(divisor);
if (divisor_size < 0) throw divide_by_zero();
int bit;
while ((bit = top_bit_set(dividend)) >= divisor_size) {
quotient.set(bit - divisor_size);
dividend ^= divisor << (bit - divisor_size); }
remainder = dividend;
return quotient;
}

implemenation of sets using bits

I am reading about sets representing as bits at following location
http://www.brpreiss.com/books/opus4/html/page395.html
class SetAsBitVector : public Set
{
typedef unsigned int Word;
enum { wordBits = bitsizeof (Word) };
Array<Word> vector;
public:
SetAsBitVector (unsigned int);
// ...
};
SetAsBitVector::SetAsBitVector (unsigned int n) :
Set (n),
vector ((n + wordBits - 1U) / wordBits)
{
// Question here?
for (unsigned int i = 0; i < vector.Length (); ++i)
vector [i] = 0;
}
void SetAsBitVector::Insert (Object& object)
{
unsigned int const item = dynamic_cast<Element&> (object);
vector [item / wordBits] |= 1 << item % wordBits;
// Question here
}
To insert an item into the set, we need to change the appropriate bit
in the array of bits to one. The ith bit of the bit array is bit i mod
w of word ceiling(i/w). Thus, the Insert function is implemented using
a bitwise or operation to change the ith bit to one as shown in above
Program . Even though it is slightly more complicated than the
corresponding operation for the SetAsArray class, the running time for
this operation is still O(1). Since w = wordBits is a power of two, it
is possible to replace the division and modulo operations, / and %,
with shifts and masks like this:
vector [item >> shift] |= 1 << (item & mask);
Depending on the compiler and machine architecture, doing so may
improve the performance of the Insert operation by a constant factor
Questions
My question in constructor why author adding wordBits to "n" and subtracting 1, instead we can use directly as n/wordbits?
Second question whay does author mean by statement "ince w = wordBits is a power of two, it is possible to replace the division and modulo operations, / and %, with shifts and masks like this:
vector [item >> shift] |= 1 << (item & mask);
Reequest to give an example in case of above scenario what is value of shift and mask.
Why author mentioned depending on architecture and compiler there is improve in performance?
I re-tagged this as C++, since it's clearly not C.
To round up. Consider what happens if you call it with n equal to something smaller than wordBits for instance. The generic formula is exactly the one being used, i.e. b = (a + Q - 1) / Q makes sure b * Q is at least a.
Basic binary arithmmetic, division by two is equivalent with shifting to the right and so on.
On some machines, bitwise operations like shifts and masks are faster than divisions and modulos.

How to Calculate 2^x mod n = 1 in less than 1 second

I want to write the program that Calculate 2^x mod n = 1 we have n is an integer but, we should calculate x.I wrote the code but my code work too slow in big n.Can you suggest me a good way that work less than 1 second to solve this problem.
here is my code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long int n,cntr=1,cheak;
cin >> n;
while (1)
{
if (n % 2 == 0)
{
break;
}
cheak=pow(2, cntr);
if (cheak % n == 1)
break;
cntr++;
}
cout << cntr << endl;
}
Some suggested modifications to your current approach: Note: a better approach follows!
Change your long long int to unsigned long long int. This will give you one more bit.
Change while (1) to while (cntr < 64). The size of unsigned long long is likely only 64 bits. (It's guaranteed to be at least 64 bits, but not larger than that.) You would then need to check whether your loop succeeded, however.
Change cheak to calculate 2n as 1ull << cntr. Make sure to include the ull suffix, which says this is an unsigned long long.
The << operator shifts bits to the left. Shifting all the bits to the left by 1 doubles the integer value of the number, assuming no bits "shifted away" off the left of the value. So, 1 << n will compute 2n.
The suffix ull indicates an integer constant is an unsigned long long. If you omit this suffix, 1 will be treated as an integer, and shift values above 31 will not do what you want.
However, all of the above are merely refinements on your current approach. It's worth understanding those refinements to better understand the language. They don't, however, look at the bigger picture.
Modular multiplication allows you to find (A * B) mod C as ( (A mod C) * (B mod C) ) mod C. How does that help us here?
We can rewrite the entire algorithm in a way that only limits N and X to the precision of the machine integers, and not 2N:
int main()
{
unsigned int modulus;
unsigned int raised = 2;
int power = 1;
std::cin >> modulus;
if (modulus % 2 == 1)
{
while (raised % modulus != 1)
{
raised = ((unsigned long long)raised * 2) % modulus;
power++;
}
std::cout << power << std::endl;
} else
{
std::cout << "modulus must be odd" << std::endl;
}
}
The cast to unsigned long long above allows modulus to be as large as 232 - 1, assuming unsigned int is 32 bits, without the computation overflowing.
With this approach, I was able to very quickly find answers even for very large inputs. For example, 111111111 returns 667332. I verified 2677332 mod 111111111 == 1 using the arbitrary precision calculator bc.
It's very fast. It computed 22323860 mod 4294967293 == 1 in less than 0.07 seconds on my computer.
Epilog: This highlights an important principle in programming: Really, this was a math problem more than a programming problem. Finding an efficient solution required knowing more about the problem domain than it did knowing about C++. The actual C++ code was trivial once we identified the correct mathematical approach.
It often goes this way, whether it's the mathematics or some other algorithmic aspect. And, it shouldn't surprise you to learn that discrete mathematics is where many of our graph and set algorithms come from. The programming language itself is a small piece of the big picture.
For each k between 1 and ceil(sqrt(n)), compute 2^k mod n and 2^(k ceil(sqrt(n))) mod n. Then compute the modular inverse of each 2^k. Sort all of the inverse(2^k)s into an array foo and the 2^(k ceil(sqrt(n))s into an array bar. There will be at least one value in common between the two arrays; find it. Say inverse(2^a) = 2^(b ceil(sqrt(n))). Then 2^(a + b ceil(sqrt(n))) = 1 (mod n).
How's your professor's sense of humor?
#include <iostream>
int main() { std::cout << 0 << '\n'; }
always prints a correct answer to the problem as stated.
pow is quite expensive in calculations, but if you have 2 as its first argument, you can better do a shift left, as shift left is equal to multiplying by 2:
cheak = (1 << cntr);

Checking whether a number is positive or negative using bitwise operators

I can check whether a number is odd/even using bitwise operators. Can I check whether a number is positive/zero/negative without using any conditional statements/operators like if/ternary etc.
Can the same be done using bitwise operators and some trick in C or in C++?
Can I check whether a number is positive/zero/negative without using any conditional statements/operators like if/ternary etc.
Of course:
bool is_positive = number > 0;
bool is_negative = number < 0;
bool is_zero = number == 0;
If the high bit is set on a signed integer (byte, long, etc., but not a floating point number), that number is negative.
int x = -2300; // assuming a 32-bit int
if ((x & 0x80000000) != 0)
{
// number is negative
}
ADDED:
You said that you don't want to use any conditionals. I suppose you could do this:
int isNegative = (x & 0x80000000);
And at some later time you can test it with if (isNegative).
Or, you could use signbit() and the work's done for you.
I'm assuming that under the hood, the math.h implementation is an efficient bitwise check (possibly solving your original goal).
Reference: http://en.cppreference.com/w/cpp/numeric/math/signbit
There is a detailed discussion on the Bit Twiddling Hacks page.
int v; // we want to find the sign of v
int sign; // the result goes here
// CHAR_BIT is the number of bits per byte (normally 8).
sign = -(v < 0); // if v < 0 then -1, else 0.
// or, to avoid branching on CPUs with flag registers (IA32):
sign = -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1));
// or, for one less instruction (but not portable):
sign = v >> (sizeof(int) * CHAR_BIT - 1);
// The last expression above evaluates to sign = v >> 31 for 32-bit integers.
// This is one operation faster than the obvious way, sign = -(v < 0). This
// trick works because when signed integers are shifted right, the value of the
// far left bit is copied to the other bits. The far left bit is 1 when the value
// is negative and 0 otherwise; all 1 bits gives -1. Unfortunately, this behavior
// is architecture-specific.
// Alternatively, if you prefer the result be either -1 or +1, then use:
sign = +1 | (v >> (sizeof(int) * CHAR_BIT - 1)); // if v < 0 then -1, else +1
// On the other hand, if you prefer the result be either -1, 0, or +1, then use:
sign = (v != 0) | -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1));
// Or, for more speed but less portability:
sign = (v != 0) | (v >> (sizeof(int) * CHAR_BIT - 1)); // -1, 0, or +1
// Or, for portability, brevity, and (perhaps) speed:
sign = (v > 0) - (v < 0); // -1, 0, or +1
// If instead you want to know if something is non-negative, resulting in +1
// or else 0, then use:
sign = 1 ^ ((unsigned int)v >> (sizeof(int) * CHAR_BIT - 1)); // if v < 0 then 0, else 1
// Caveat: On March 7, 2003, Angus Duggan pointed out that the 1989 ANSI C
// specification leaves the result of signed right-shift implementation-defined,
// so on some systems this hack might not work. For greater portability, Toby
// Speight suggested on September 28, 2005 that CHAR_BIT be used here and
// throughout rather than assuming bytes were 8 bits long. Angus recommended
// the more portable versions above, involving casting on March 4, 2006.
// Rohit Garg suggested the version for non-negative integers on September 12, 2009.
#include<stdio.h>
void main()
{
int n; // assuming int to be 32 bit long
//shift it right 31 times so that MSB comes to LSB's position
//and then and it with 0x1
if ((n>>31) & 0x1 == 1) {
printf("negative number\n");
} else {
printf("positive number\n");
}
getch();
}
Signed integers and floating points normally use the most significant bit for storing the sign so if you know the size you could extract the info from the most significant bit.
There is generally little benefit in doing this this since some sort of comparison will need to be made to use this information and it is just as easy for a processor to tests whether something is negative as it is to test whether it is not zero. If fact on ARM processors, checking the most significant bit will be normally MORE expensive than checking whether it is negative up front.
It is quite simple
It can be easily done by
return ((!!x) | (x >> 31));
it returns
1 for a positive number,
-1 for a negative, and
0 for zero
This can not be done in a portable way with bit operations in C. The representations for signed integer types that the standard allows can be much weirder than you might suspect. In particular the value with sign bit on and otherwise zero need not be a permissible value for the signed type nor the unsigned type, but a so-called trap representation for both types.
All computations with bit operators that you can thus do might have a result that leads to undefined behavior.
In any case as some of the other answers suggest, this is not really necessary and comparison with < or > should suffice in any practical context, is more efficient, easier to read... so just do it that way.
// if (x < 0) return -1
// else if (x == 0) return 0
// else return 1
int sign(int x) {
// x_is_not_zero = 0 if x is 0 else x_is_not_zero = 1
int x_is_not_zero = (( x | (~x + 1)) >> 31) & 0x1;
return (x & 0x01 << 31) >> 31 | x_is_not_zero; // for minux x, don't care the last operand
}
Here's exactly what you waht!
Here is an update related to C++11 for this old question. It is also worth considering std::signbit.
On Compiler Explorer using gcc 7.3 64bit with -O3 optimization, this code
bool s1(double d)
{
return d < 0.0;
}
generates
s1(double):
pxor xmm1, xmm1
ucomisd xmm1, xmm0
seta al
ret
And this code
bool s2(double d)
{
return std::signbit(d);
}
generates
s2(double):
movmskpd eax, xmm0
and eax, 1
ret
You would need to profile to ensure that there is any speed difference, but the signbit version does use 1 less opcode.
When you're sure about the size of an integer (assuming 16-bit int):
bool is_negative = (unsigned) signed_int_value >> 15;
When you are unsure of the size of integers:
bool is_negative = (unsigned) signed_int_value >> (sizeof(int)*8)-1; //where 8 is bits
The unsigned keyword is optional.
if( (num>>sizeof(int)*8 - 1) == 0 )
// number is positive
else
// number is negative
If value is 0 then number is positive else negative
A simpler way to find out if a number is positive or negative:
Let the number be x
check if [x * (-1)] > x. if true x is negative else positive.
You can differentiate between negative/non-negative by looking at the most significant bit.
In all representations for signed integers, that bit will be set to 1 if the number is negative.
There is no test to differentiate between zero and positive, except for a direct test against 0.
To test for negative, you could use
#define IS_NEGATIVE(x) ((x) & (1U << ((sizeof(x)*CHAR_BIT)-1)))
Suppose your number is a=10 (positive). If you shift a a times it will give zero.
i.e:
10>>10 == 0
So you can check if the number is positive, but in case a=-10 (negative):
-10>>-10 == -1
So you can combine those in an if:
if(!(a>>a))
print number is positive
else
print no. is negative
#include<stdio.h>
int checksign(int n)
{
return (n >= 0 && (n & (1<<32-1)) >=0);
}
void main()
{
int num = 11;
if(checksign(num))
{
printf("Unsigned number");
}
else
{
printf("signed Number");
}
}
Without if:
string pole[2] = {"+", "-"};
long long x;
while (true){
cin >> x;
cout << pole[x/-((x*(-1))-1)] << "\n\n";
}
(not working for 0)
if(n & (1<<31))
{
printf("Negative number");
}
else{
printf("positive number");
}
It check the first bit which is most significant bit of the n number and then & operation is work on it if the value is 1 which is true then the number is negative and it not then it is positive number