Binary long division algorithm - java

I have been trying to recreate the following algorithm in java:
Set quotient to 0
Align leftmost digits in dividend and divisor
Repeat
If that portion of the dividend above the divisor is greater than or equal to the divisor
Then subtract divisor from that portion of the dividend and
Concatentate 1 to the right hand end of the quotient
Else concatentate 0 to the right hand end of the quotient
Shift the divisor one place right
Until dividend is less than the divisor
quotient is correct, dividend is remainder
STOP
This can also be found here:
Here is my code:
public class Division {
public static void main(String[] args) {
int quotient =0;
int a = 123;
int b = 5;
int bfirst = b;
String a1 = Integer.toBinaryString(a);
String b1 = Integer.toBinaryString(b);
int aLength = a1.length();
int bLength = b1.length();
int power = aLength - bLength;
b =(int) Math.pow(b, power);
while(a > bfirst) {
if(a >= b) {
a = a-b;
quotient = quotient*2+1;
b = b/2;
} else {
quotient = quotient*2;
b = b/2;
}
}
System.out.println(quotient);
}
}
It sometimes returns answers which are right, but other times will not. Any ideas?

I believe
b = (int) Math.pow(b, power);
should be
b = (int) (b * Math.pow(2, power));
The variable b appears to be the current digit to be compared with, and got subtracted by a. You are doing binary division, and in the code following this line I found this value were only divided by 2. In this case, Math.pow(b, power) does not make sense.
Furthermore, there is a missing step. Because a - b will bring all the values down to the end and get a < bFirst, all ending zeroes are not counted into quotient, as we have already exited the loop.
Replace
a = a-b;
quotient = quotient*2+1;
b = b/2;
with
bLength = Integer.toBinaryString(b).length();
int bfirstLength = Integer.toBinaryString(bfirst).length();
a = a-b;
quotient = quotient*2+1;
b = b/2;
if (a < bfirst) {
quotient = quotient * (int)Math.pow(2, bLength - bfirstLength);
}
To account for missing zeroes of the quotient.
Furthermore there is an Off-by-one-error.
while (a > bfirst) {
should be
while (a >= bfirst) {
If a is divisible by b, long division should go ahead and subtract the remaining dividend, instead of stopping the procedure.
Finally, number of binary digits in a number can be computed by
(int) (Math.ln(a) / Math.ln(2)) + 1
Last, try to make use of System.out.println inside your algorithm when debugging, it helps a lot and let you precisely know where your algorithm goes wrong. Better, if you know how and is available (usually integrated into IDEs), use a debugger.
And, the last one, do the algorithm by hand with some examples before coding - this can definitely help you understand how the algorithm works.
The entire thing, with debug statements: http://ideone.com/JBzHdf

Your algorithm isn't quite correct. It will fail if the quotient has trailing zeros because the loop stops before it has appended them. A correct algorithm is:
let q = 0
shift divisor left until divisor > dividend (k bits)
while k > 0
k = k - 1
divisor = divisor >> 1
if dividend >= divisor
q = (q << 1) + 1
dividend = dividend - sd
else
q = q << 1
return q
You should really use integers (type long in fact) and the shift operators << and >>. They make this much easier (not to mention faster) then the string operations.
Since an answer is already accepted, here is Java for the algorithm above in case of interest.
public static long div(long dividend, long divisor) {
long quotient = 0;
int k = 0;
while (divisor <= dividend && divisor > 0) {
divisor <<= 1;
k++;
}
while (k-- > 0) {
divisor >>= 1;
if (divisor <= dividend) {
dividend -= divisor;
quotient = (quotient << 1) + 1;
}
else quotient <<= 1;
}
return quotient;
}

Related

How to get the correct output in Modulo (10^9 + 7) format?

I am working on this code challenge:
Problem Description
Given 2 integers x and n, you have to calculate x
to the power of n, modulo 10^9+7 i.e. calculate (x^n) % (10^9+7).
In other words, you have to find the value when x is raised to the
power of n, and then modulo is taken with 10^9+7.
a%b means the remainder when a divides b. For instance, 5%3 = 2, as
when we divide 5 by 3, 2 is the remainder.
Note that 10^9 is also represented as 1e9.
Input format
One line of input containing two space separated
integers, x and n.
Output format Print the required answer.
Sample Input 1 100000000 2
Sample Output 1 930000007
Explanation 1 (10^8)^2 = 10^16
10^16 % (10^9+7) = 930000007
Constraints 0 <= x < 10^9
0 <= n < 10^5
Code
The following is my code:
import java.util.*;
class ModularExponentiation {
// NOTE: Please do not modify this function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int n = sc.nextInt();
int ans = modularExponentiation(x, n);
System.out.println(ans);
}
// TODO: Implement this method
static int modularExponentiation(int x, int n) {
int M = 1000000007;
long a = (long) Math.pow(x, n);
long b = a%M;
return (int)b;
}
}
When I run my code, it succeeds for the sample test case and an edge case, but fails for 3 base cases. How do I make my code succeed all test cases?
Does this work?
public static int modularExponentiation(int x, int n) {
int modulo = 1000000007;
if (n == 0) {
return 1;
} else if (n == 1) {
return x % modulo;
} else if (n == -1) {
return 1 / x;
}
int p = modularExponentiation(x, n >> 1);
long product = ((long) p * p) % modulo;
return (int) (product * modularExponentiation(x, n & 1) % modulo);
}
Key points:
Math.pow(x,n) suffers from overflow and we can't compensate that overflow relying on result only, that is why initial idea of Math.pow(x,n) % modulo produces wrong results
We may notice that (x * x) % modulo == (x % modulo) * (x % modulo) % modulo, and it is safe to use long here as intermediate result because x % modulo < modulo and modulo * modulo < 2^63 - 1
We need to reconstruct the process, but naive approach that x^n is a product of n x's is too slow - it has O(N) time complexity, however we may notice that x^2k == (x^k)^2 and x^(2k+1) == x * (x^k)^2 - so we may use either recursion here or loop to achieve O(LogN) time complexity
alternative loop solution:
public static int modularExponentiation(int x, int n) {
int modulo = 1000000007;
long product = 1;
long p = x;
while (n != 0) {
if ((n & 1) == 1) {
product = product * p % modulo;
}
p = (p * p % modulo);
n >>= 1;
}
return (int) product;
}
If you have problem in C++ then , you can use
const unsigned int Mod=1e9+7;

LeetCode Divide Two Integers - Repeated Exponential Searches solution with negative numbers

I am having hard time understanding below solution in leetcode. Why int powerOfTwo = -1 is initialized with -1 as we have already handled divide(INT_MIN, -1) case
:
Adding problem statement -
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
Note:
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For this problem, assume that your function returns 2^31 − 1 when the division result overflows.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.
https://leetcode.com/problems/divide-two-integers/solution/
private static int HALF_INT_MIN = -1073741824;
public int divide(int dividend, int divisor) {
// Special case: overflow.
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
/* We need to convert both numbers to negatives.
* Also, we count the number of negatives signs. */
int negatives = 2;
if (dividend > 0) {
negatives--;
dividend = -dividend;
}
if (divisor > 0) {
negatives--;
divisor = -divisor;
}
int quotient = 0;
/* Once the divisor is bigger than the current dividend,
* we can't fit any more copies of the divisor into it. */
while (divisor >= dividend) {
/* We know it'll fit at least once as divivend >= divisor.
* Note: We use a negative powerOfTwo as it's possible we might have
* the case divide(INT_MIN, -1). */
int powerOfTwo = -1;
int value = divisor;
/* Check if double the current value is too big. If not, continue doubling.
* If it is too big, stop doubling and continue with the next step */
while (value >= HALF_INT_MIN && value + value >= dividend) {
value += value;
powerOfTwo += powerOfTwo;
}
// We have been able to subtract divisor another powerOfTwo times.
quotient += powerOfTwo;
// Remove value so far so that we can continue the process with remainder.
dividend -= value;
}
/* If there was originally one negative sign, then
* the quotient remains negative. Otherwise, switch
* it to positive. */
if (negatives != 1) {
return -quotient;
}
return quotient;
}

decimal value of the number formed by concatenating the binary representations of first n natural numbers

Given a number n, find the decimal value of the number formed by concatenating the binary representations of first n natural numbers.
Print answer modulo 10^9+7.
Also, n can be as big as 10^9 and hence logarithmic time approach is needed.
Eg: n=4, Answer = 220
Explanation: Number formed=11011100 (1=1,2=10,3=11,4=100).
Decimal value of 11011100="220".
The code I am using below only works for first integers N<=15
String input = "";
for(int i = 1;i<=n;i++) {
input += (Integer.toBinaryString(i));
}
return Integer.parseInt(input,2);
This solution to this question requires O(N) time. Luckily this can be solved in O(logN) time. Also, this is the A047778 sequence:
1,6,27,220,1765,14126,113015,1808248,28931977, 462911642,7406586283,118505380540,1896086088653, 30337377418462,485398038695407,15532737238253040, 497047591624097297,15905522931971113522
The sequence follows this recurrence relation:
where ⌊.⌋ is floor function
a(n) can also be expressed as sum of multiple arithmetico–geometric series.
If we are interested in a(14), here's how it can be calculated.
Multiplying with powers of two on both sides of the above equations gives equations like the following:
If we add all the above equations, a(14) can be expressed as sum of four arithmetico–geometric series.
It's important to note that in all sequences except the first one, the first term of the arithmetic progression is of form and the last term
The sum of n terms of arithmetico–geometric sequence can be calculated using this formula :
a(First term of AP), n(Number of terms), d(Common Difference of AP), b(First term of GP), r(Common ratio of GP).
Since we're interested in a(n) mod 1000000007 and not the actual term a(n), these modulo arithmetics may come in handy.
This is a good starting point for implementing division modulo which requires some number theory basics.
Once we figure out the number of sequences required and the five variables a, n, d, b, r for each sequence, a(n) modulo 1000000007 can be calculated in O(logn) time.
Here's a working C++ code :
#include <numeric>
#include <iostream>
#define mod long(1e9+7)
long multiply(long a,long b){
a%= mod;b%= mod;
return (a*b)%mod;
}
void inverseModulo(long a,long m,long *x,long *y){ //ax congruent to 1 mod m
if(!a){
*x=0;
*y=1;
return ;
}
long x1,y1;
inverseModulo(m%a,a,&x1,&y1);
*x=y1-(m/a)*x1;
*y=x1;
return;
}
long moduloDivision(long a,long b,long m){ // (a*(returnValue))mod m congruent to b mod m
//https://www.geeksforgeeks.org/modular-division/ and https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
long x,y;
inverseModulo(b, m, &x, &y);
x%=m;
return (x*a)%m;
}
long power(long n,long r){ //calculates (n^r)%mod in logarithmic time
if(r==0) return 1;
if(r==1) return n;
if(r%2){
auto tmp=power(n, (r-1)/2);
return multiply(multiply(n,tmp),tmp);
}
auto tmp=power(n, r/2);
return multiply(tmp, tmp);
}
long sumOfAGPSeries(long a,long d,long b,long r,long n){
if(r==1) return multiply(n, multiply(a, 2)+multiply(n-1, d))/2;
long left=multiply(multiply(d, r), power(r,n-1)-1);
left=a+moduloDivision(left,r-1,mod);
left=multiply(left, b);
left%=mod;
long right=multiply(multiply(b, power(r, n)), a+multiply(n-1, d));
long ans=right-left;
ans=(ans%mod + mod) % mod;
return moduloDivision(ans,r-1,mod);
}
signed main(){
long N=1000;
long ans = 0;
long bitCountOfN = log2(N) + 1;
long nearestPowerOfTwo = pow(2, bitCountOfN - 1);
long startOfGP = 0;
while (nearestPowerOfTwo) { // iterating over each arithmetico–geometric sequence
long a, d, b, r, n;
a = N;
d = -1;
b = power(2, startOfGP);
r = power(2, bitCountOfN);
n = N - nearestPowerOfTwo + 1;
ans += sumOfAGPSeries(a, d, b, r, n);
ans %= mod;
startOfGP += n * bitCountOfN;
N = nearestPowerOfTwo - 1;
nearestPowerOfTwo >>= 1;
bitCountOfN--;
}
std::cout << ans << std::endl;
return 0;
}
The validity of the above C++ code can be verified using this trivial python code :
def a(n):
return int("".join([(bin(i))[2:] for i in range(1, n+1)]), 2)
for n in range(1,100):
print (a(n)%1000000007)
Note that working with string representation is not necessary (moreover, is not useful after task changing). Look at approach with bitwise arithmetics (Python, but principle is the same)
With new condition concerning modulo 1000000007 we have just add modulo operation to result calculation line at every step, because shift left and or-ing is equivalent to multiplication by power of two and adding, these operations are obeyed to equivalence relations for modulo properties. Note that intermediate results don't exceed 1000000007*n, so long type is suitable here for reasonable n values.
n = 100
size = 0 #bit length of addends
result = 0 # long accumulator
for i in range(1, n + 1):
if i & (i - 1) == 0: #for powers of two we increase bit length
size += 1
result = ((result << size) | i) % 1000000007 #shift accumulator left and fill low bits with new addend
print(result)
variant without bitwise operations:
pow2 = 1
nextpow = 2
result = 0 # long accumulator
for i in range(1, n + 1):
if i == nextpow: #for powers of two we increase bit length
pow2 = nextpow
nextpow = nextpow * 2
result = (result * pow2 + i) % 1000000007 #shift accumulator left and fill low bits with new addend
cin>>n;
ll ans=1;
ll one=1;
for(int i=2;i<=n;i++)
{
ll digit=log2(i)+1;
ans=(((ans%N*(one<<digit)%N)%N+i%N)%N);
}
cout<<ans<<Ed;

Divide two integers without using multiplication, division and mod operator in java

I write down a code which find out quotient after dividing two number but without using multiplication,division or mod operator.
My code
public int divide(int dividend, int divisor) {
int diff=0,count=0;
int fun_dividend=dividend;
int fun_divisor=divisor;
int abs_dividend=abs(dividend);
int abs_divisor=abs(divisor);
while(abs_dividend>=abs_divisor){
diff=abs_dividend-abs_divisor;
abs_dividend=diff;
count++;
}
if(fun_dividend<0 && fun_divisor<0){
return count;
}
else if(fun_divisor<0||fun_dividend<0) {
return (-count);
}
return count;
}
My code passes the test cases like dividend=-1, divisor=1 or dividend=1 and divisor=-1. But it cannot pass the test case like dividend = --2147483648 and divisor =-1. However I have a if statement when both inputs are negative.
if(fun_dividend<0 && fun_divisor<0){
return count;
}
When my inputs are -2147483648 and -1 it returned zero. I debugged my code and find out that it cannot reach the the inner statements of while loop. It just check the while loop and terminated and execute
if(fun_dividend<0 && fun_divisor<0){
return count;
}
It is very obvious, both inputs are negative, so I was using Math.abs function to make them positive. But when I try to see the values of variables abs_dividend and abs_divisor they show me negative values.
Integer max can take a 9 digit number. So how could I pass this test case? As per this test case dividend is a 10 digit number which is not valid for a integer range.
As per the test case the output that I get should be 2147483647.
How could I solve the bug?
Thank you in advance.
Try using the bit manipulation for this as follows:
public static int divideUsingBits(int dividend, int divisor) {
// handle special cases
if (divisor == 0)
return Integer.MAX_VALUE;
if (divisor == -1 && dividend == Integer.MIN_VALUE)
return Integer.MAX_VALUE;
// get positive values
long pDividend = Math.abs((long) dividend);
long pDivisor = Math.abs((long) divisor);
int result = 0;
while (pDividend >= pDivisor) {
// calculate number of left shifts
int numShift = 0;
while (pDividend >= (pDivisor << numShift)) {
numShift++;
}
// dividend minus the largest shifted divisor
result += 1 << (numShift - 1);
pDividend -= (pDivisor << (numShift - 1));
}
if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) {
return result;
} else {
return -result;
}
}
I solve it this way. Give preference to data type long over int wherever there is a chance of overflow upon left-shift. Handle the edge case at the very beginning to avoid the input values getting modified in the process. This algorithm is based upon the division technique we used to make use in school.
public int divide(int AA, int BB) {
// Edge case first.
if (BB == -1 && AA == Integer.MIN_VALUE){
return Integer.MAX_VALUE; // Very Special case, since 2^31 is not inside range while -2^31 is within range.
}
long B = BB;
long A = AA;
int sign = -1;
if ((A<0 && B<0) || (A>0 && B>0)){
sign = 1;
}
if (A < 0) A = A * -1;
if (B < 0) B = B * -1;
int ans = 0;
long currPos = 1; // necessary to be long. Long is better for left shifting.
while (A >= B){
B <<= 1; currPos <<= 1;
}
B >>= 1; currPos >>= 1;
while (currPos != 0){
if (A >= B){
A -= B;
ans |= currPos;
}
B >>= 1; currPos >>= 1;
}
return ans*sign;
}
Ran with the debugger and found that abs_dividend was -2147483648.
Then the comparison in while (abs_dividend >= abs_divisor) { is false and count is never incremented.
Turns out the explanation is in the Javadoc for Math.abs(int a):
Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
Presumably, this is because Integer.MAX_VALUE is 2147483647, so there is no way of representing positive 2147483648 with an int. (note: 2147483648 would be Integer.MAX_VALUE + 1 == Integer.MIN_VALUE)

Not using % or any java built in methods (math), how to do modulo exponentiation?

So I need to do modulo exponentiation using 2^N mod M, but I cant use % or any built in java.math or Math method. Applying mod M as 2^N increases seems* like it would work. But is doesn't seem to ( or im just doing it wrong...)
int N = 63;
int M = 1000;
int result;
while (n > 0)
{
power *= 2;
n --;
// this part defn doesnt work... best idea so far
if (power >M)
{
result = power - m;
}
}
Per §15.17.3 "Remainder Operator %" of The Java Language Specification, Java SE 7 Edition, (a/b)*b+(a%b) is always equal to a. Turning this around, we have a%b == a - (a/b)*b. So, you should be able to write:
power *= 2;
power -= (power/M) * M;
Or, since you're only multiplying by two each time, you know that power cannot exceed M before this operation, so you can rewrite the above as:
power *= 2;
if (power > M) {
power -= M;
}
Maybe power -= m instead of result = power - m?
Since BigInteger.modPow already implements this, you should just look at the source code of BigInteger.
Annotated code:
int M = 13;
int result = 2;
int n = 10;
while (--n > 0) // do n iterations multiplying the number with 2
result *= 2;
if (M < 0) // safe guard if someone gives you a negative M then flip it
M *= -1;
while ((result-M) >= 0) // keep subtracting M until right before it turns negative
result -= M;
Remember though, that integers are not big enough for 2^63 like your code shows you're trying to do. ints are 32 bit signed, so 2^31 to -2^31-1 is the range.
Your version seems also to do modulus on each iteration of multiplication. You can do that, too. And it will allow you to use 2^63 like your code tries:
int M = 13;
int result = 2;
int n = 10;
if (M < 0)
M *= -1;
while (--n > 0) {
result *= 2;
while ((result-M) >= 0)
result -= M;
}
Assumptions: power and modulo > 0, a validation should be in place before calling this method.
long modPow(long x, long power, long modulo) {
if (power > 1) {
x = modPow(x, power / 2, modulo) * modPow(x, (power + 1) / 2, modulo);
}
return x - x / modulo * modulo;
}
call it:
result = modPow(2, power, modulo);
Here is a recursive version. If power is too big to handle it, we split it in 2. We then return x % modulo(inspired by "ruakh example"). We also know that:
y = y / 2 + (y + 1) / 2
so
x^n = x^(n/2) * x^[(n+1)/2]
This way, we know that every modPow call will return a number smaller than modulo every time.
Advantages? Parallelization and if you want to make things even fancier, add memoisation.
You can easily convert my version in a Fork / Join model, you can find more details about it here
Haven't you noticed that it is the power of 2 ? Why hadn't you used it?
2^N mod M is to be counted as
long power=1L << N;
long temp=power/M;
long result= power-temp*M;
You can just use power-=M as the modulo is nothing but continuous subtraction of the divisor from divident until the divident<divisor.
The below should work
public class HelloWorld{
public static void main(String []args){
int N = 63;
int M = 1000;
long result=0;
long power=1;
for(int i=0;i<N;i++)
{
power *= 2;
N--;
if (power >=M)
{
power = power - M;
}
}
System.out.println("power:"+power);
}
}

Categories