I'm curious about the GCD problem. I am taking the Coursera Algorithmic toolbox course, and it states that the naive solution to the problem is:
for d from 1 to a+b:
if d|a and d|b:
best(or max) d
return best
I'm confused by this though. Wouldn't the maximum possible divisor be min(a,b) instead of a+b? since the smaller of the two couldn't possibly be divided by the larger of the two?
Yes, you are right. You could rewrite the algorithm, that the loop stop by min(a,b)
for d from 1 to min(a,b):
if d|a and d|b:
best(or max) d
return best
This implementation is faster than the first one. You could still improve it by looping backward:
for d from min(a,b) to 1:
if d|a and d|b:
break
return d
Related
I don't know whether I used the unpredictive word correctly or not. But here's the problem:
I have a rectangular piece of paper of length a and breadth b. I will keep cutting the squares from it, of side equal to min(a,b) until the last square is of unit length. Determine the number of squares I can cut.
Here's my algorithm :
#include <iostream>
using namespace std;
int main()
{
long long a,b,temp,small,large,res;
cin >> a >> b;
res = 0;
small = min(a,b);
large = a + b - small;
while(small > 0 && small != large)
{
res = res + large/small;
temp = large % small;
large = small;
small = temp;
}
cout << res;
return 0;
}
I am confused how to calculate time complexity in this case, as max(a,b) decreases to 1, in non-even fashion, depending upon the initial values of a and b. The best case would definitely be when, either or both of them is 1 already. The worst case would be, I guess, when both are prime. Please help me to analyze the time complexity.
This algorithm is very similar to the Euclidean algorithm for computing the greatest common divisor. Recall that that algorithm works by:
Start with two numbers a, b, assume without loss than a >= b. If a == b then stop.
In the next round, the two numbers are b and a % b instead.
Now consider your algorithm. It's the same, except it's a - b instead. But this will actually do the same thing if a < 2 * b. And if a < k * b, then in the next round it changes only by a multiple of b, so after at most k rounds, it will converge to a % b. So this is just a slower version of the Euclidean algorithm.
The time complexity of the Euclidean algorithm is quite fast -- since it's repeated division, the number of rounds is not more than the number of digits.
Edit: To expand on last part:
To analyze the time complexity, a first question is, how many rounds does it take.
An easy way to start is, if a and b have n and m digits in their (binary) description, then there can't be more than n + m rounds. Because, as long as b is at least two in a given round, we will be dividing one of the numbers by two in that round, so the result will have one less digit. If b is one, then this is the last round.
A second question is, how much time does it take to do a single round.
If you are satisfied with "the running time is at most polynomial in the number of digits", then this is now clear, since you can easily do division in polynomial in the number of digits.
I'm not actually sure what the tightest analysis possible is. You might be able to do some kind of win-win analysis to improve on this, I'm almost sure this has been studied but I don't know a reference, sorry.
I'm looking to calculate the following sum efficiently:
sum (i=0..max) (i * A mod B)
One may assume that max, A < B and that A and B are co-prime (otherwise an easy reduction is possible). Numbers are large, so simple iteration is way too inefficient.
So far I haven't been able to come up with a polynomial-time algorithm (i.e., polynomial in log(B)), best I could find is O(sqrt(max)). Is this a known hard problem, or does anyone know of a polynomial-time algorithm?
To be clear, the "mod B" only applies to the i*A, not to the overall sum. So e.g.
sum(i=0..3) (i*7 mod 11) = 0 + 7 + 3 + 10 = 20.
You can shift things around a bit to get
A*(sum(i=0..max)) mod B
which simplifies to
A*(max*(max+1)/2) mod B
Now you only need to do one (possibly big-int) multiplication (assuming max itself isn't too big) followed by one (big-int) mod operation.
I've found similar questions but this is a bit more complicated.
I have a large number n(I actually have more, but it doesn't matter now), (>40 digits), and I want to find a*b*c=n triplets. n's prime factorisation is done. It has no large prime divisors, but many of small prime divisors. The sum of all prime divisors (included multiple divisors) is greater than 50.
I'd like to find a*b*c=n triplets, where a<=b<=c. I don't want all the triplets, because there are too much of them. I'm searching for special ones.
For example:
the triplet(s) where c-a is minimal,
the triplet(s) where c/a minimal,
the one where a,b and c has the maximal common divisor,
these conditions combined.
This can be a little easier to solve if we know that n=k!(factorial). Solving could lead to a general method.
Computing all these triplets with brute force is not an option because of the size of n, so i need a good algorithm or some special tools to help me implement a solution for this.
Sorry for my bad English,
Thanks for the answers!
You can achieve it with a simple, O(|D|^2) algorithms, where D is an ordered list of all the numbers dividing n, which you already have.
Note that you only have to find a,b, because c=n/(a*b), so the problems boils down to finding all the pairs (a,b) in D so that a<b and n/(a*b) ∈ D.
Pseudocode:
result = empty_list
for (int i=0; i<D.size-1, i++) { // O(|D|)
for (j=i+1; j<D.size, j++) { // O(|D|)
a, b = D[i], D[j]
c = n/(a*b)
if (D.contains(c) && c>b) { // O(1)
result.append( (a,b,c) )
}
}
} // O(|D|)*O(|D|)=O(|D|^2)
I might have the solution, but I have no time to implement it today. I write it down, so maybe somebody will agree with me or will spot the weak point of my algorithm.
So let's see the first or second case, where c/a or c-a should be minimal.
1: In first step I split the prime factors of n to 3 group with a greedy algorithm.
I will have an initial a,b and c and they will be not very far from each other. The prime factors will be stored in 3 arrays: a_pf,b_pf,c_pf.
2: In next step I compute all the possible factors for a,b and c, I store them in different arrays, then I order these arrays. These will be a_all,b_all and c_all.
3: I compute q=max(a,b,c)/min(a,b,c). (now we can say that a is the smallest, c is the greatest number)
4: I search a_all and c_all for numbers on this condiition: c_all[i]/a_all[j] < q. When I find it, I change the prime factors of these values in a_pf and c_pf. With this method, the largest and the smallest member of the triplet will come closer to each other.
I repeat step 2-3-4, until I can. I think this will end after finite number of steps.
Since the triplet's members are smaller than the original n, I hope this solution will give me the correct triplet at most in a few minutes.
I've been trying to implement a modular exponentiator recently. I'm writing the code in VHDL, but I'm looking for advice of a more algorithmic nature. The main component of the modular exponentiator is a modular multiplier which I also have to implement myself. I haven't had any problems with the multiplication algorithm- it's just adding and shifting and I've done a good job of figuring out what all of my variables mean so that I can multiply in a pretty reasonable amount of time.
The problem that I'm having is with implementing the modulus operation in the multiplier. I know that performing repeated subtractions will work, but it will also be slow. I found out that I could shift the modulus to effectively subtract large multiples of the modulus but I think there might still be better ways to do this. The algorithm that I'm using works something like this (weird pseudocode follows):
result,modulus : integer (n bits) (previously defined)
shiftcount : integer (initialized to zero)
while( (modulus<result) and (modulus(n-1) != 1) ){
modulus = modulus << 1
shiftcount++
}
for(i=shiftcount;i>=0;i--){
if(modulus<result){result = result-modulus}
if(i!=0){modulus = modulus >> 1}
}
So...is this a good algorithm, or at least a good place to start? Wikipedia doesn't really discuss algorithms for implementing the modulo operation, and whenever I try to search elsewhere I find really interesting but incredibly complicated (and often unrelated) research papers and publications. If there's an obvious way to implement this that I'm not seeing, I'd really appreciate some feedback.
I'm not sure what you're calculating there to be honest. You talk about modulo operation, but usually a modulo operation is between two numbers a and b, and its result is the remainder of dividing a by b. Where is the a and b in your pseudocode...?
Anyway, maybe this'll help: a mod b = a - floor(a / b) * b.
I don't know if this is faster or not, it depends on whether or not you can do division and multiplication faster than a lot of subtractions.
Another way to speed up the subtraction approach is to use binary search. If you want a mod b, you need to subtract b from a until a is smaller than b. So basically you need to find k such that:
a - k*b < b, k is min
One way to find this k is a linear search:
k = 0;
while ( a - k*b >= b )
++k;
return a - k*b;
But you can also binary search it (only ran a few tests but it worked on all of them):
k = 0;
left = 0, right = a
while ( left < right )
{
m = (left + right) / 2;
if ( a - m*b >= b )
left = m + 1;
else
right = m;
}
return a - left*b;
I'm guessing the binary search solution will be the fastest when dealing with big numbers.
If you want to calculate a mod b and only a is a big number (you can store b on a primitive data type), you can do it even faster:
for each digit p of a do
mod = (mod * 10 + p) % b
return mod
This works because we can write a as a_n*10^n + a_(n-1)*10^(n-1) + ... + a_1*10^0 = (((a_n * 10 + a_(n-1)) * 10 + a_(n-2)) * 10 + ...
I think the binary search is what you're looking for though.
There are many ways to do it in O(log n) time for n bits; you can do it with multiplication and you don't have to iterate 1 bit at a time. For example,
a mod b = a - floor((a * r)/2^n) * b
where
r = 2^n / b
is precomputed because typically you're using the same b many times. If not, use the standard superconverging polynomial iteration method for reciprocal (iterate 2x - bx^2 in fixed point).
Choose n according to the range you need the result (for many algorithms like modulo exponentiation it doesn't have to be 0..b).
(Many decades ago I thought I saw a trick to avoid 2 multiplications in a row... Update: I think it's Montgomery Multiplication (see REDC algorithm). I take it back, REDC does the same work as the simpler algorithm above. Not sure why REDC was ever invented... Maybe slightly lower latency due to using the low-order result into the chained multiplication, instead of the higher-order result?)
Of course if you have a lot of memory, you can just precompute all the 2^n mod b partial sums for n = log2(b)..log2(a). Many software implementations do this.
If you're using shift-and-add for the multiplication (which is by no means the fastest way) you can do the modulo operation after each addition step. If the sum is greater than the modulus you then subtract the modulus. If you can predict the overflow, you can do the addition and subtraction at the same time. Doing the modulo at each step will also reduce the overall size of your multiplier (same length as input rather than double).
The shifting of the modulus you're doing is getting you most of the way towards a full division algorithm (modulo is just taking the remainder).
EDIT Here is my implementation in Python:
def mod_mul(a,b,m):
result = 0
a = a % m
b = b % m
while (b>0):
if (b&1)!=0:
result += a
if result >= m: result -= m
a = a << 1
if a>=m: a-= m
b = b>>1
return result
This is just modular multiplication (result = a*b mod m). The modulo operations at the top are not needed, but serve as a reminder that the algorithm assumes a and b are less than m.
Of course for modular exponentiation you'll have an outer loop that does this entire operation at each step doing either squaring or multiplication. But I think you knew that.
For modulo itself, I'm not sure. For modulo as part of the larger modular exponential operation, did you look up Montgomery multiplication as mentioned in the wikipedia page on modular exponentiation? It's been a while since I've looked into this type of algorithm, but from what I recall, it's commonly used in fast modular exponentiation.
edit: for what it's worth, your modulo algorithm seems ok at first glance. You're basically doing division which is a repeated subtraction algorithm.
That test (modulus(n-1) != 1) //a bit test?
-seems redundant combined with (modulus<result).
Designing for hardware implementation i would be conscious of the smaller/greater than tests implying more logic (subtraction) than bitwise operations and branching on zero.
If we can do bitwise tests easily, this could be quick:
m=msb_of(modulus)
while( result>0 )
{
r=msb_of(result) //countdown from prev msb onto result
shift=r-m //countdown from r onto modulus or
//unroll the small subtraction
takeoff=(modulus<<(shift)) //or integrate this into count of shift
result=result-takeoff; //necessary subtraction
if(shift!=0 && result<0)
{ result=result+(takeoff>>1); }
} //endwhile
if(result==0) { return result }
else { return result+takeoff }
(code untested may contain gotchas)
result is repetively decremented by modulus shifted to match at most significant bits.
After each subtraction: result has a ~50/50 chance of loosing more than 1 msb. It also has ~50/50 chance of going negative,
addition of half what was subtracted will always put it into positive again. > it should be put back in positive if shift was not=0
The working loop exits when result is underrun and 'shift' was 0.
Given positive integers b, c, m where (b < m) is True it is to find a positive integer e such that
(b**e % m == c) is True
where ** is exponentiation (e.g. in Ruby, Python or ^ in some other languages) and % is modulo operation. What is the most effective algorithm (with the lowest big-O complexity) to solve it?
Example:
Given b=5; c=8; m=13 this algorithm must find e=7 because 5**7%13 = 8
From the % operator I'm assuming that you are working with integers.
You are trying to solve the Discrete Logarithm problem. A reasonable algorithm is Baby step, giant step, although there are many others, none of which are particularly fast.
The difficulty of finding a fast solution to the discrete logarithm problem is a fundamental part of some popular cryptographic algorithms, so if you find a better solution than any of those on Wikipedia please let me know!
This isn't a simple problem at all. It is called calculating the discrete logarithm and it is the inverse operation to a modular exponentation.
There is no efficient algorithm known. That is, if N denotes the number of bits in m, all known algorithms run in O(2^(N^C)) where C>0.
Python 3 Solution:
Thankfully, SymPy has implemented this for you!
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python.
This is the documentation on the discrete_log function. Use this to import it:
from sympy.ntheory import discrete_log
Their example computes \log_7(15) (mod 41):
>>> discrete_log(41, 15, 7)
3
Because of the (state-of-the-art, mind you) algorithms it employs to solve it, you'll get O(\sqrt{n}) on most inputs you try. It's considerably faster when your prime modulus has the property where p - 1 factors into a lot of small primes.
Consider a prime on the order of 100 bits: (~ 2^{100}). With \sqrt{n} complexity, that's still 2^{50} iterations. That being said, don't reinvent the wheel. This does a pretty good job. I might also add that it was almost 4x times more memory efficient than Mathematica's MultiplicativeOrder function when I ran with large-ish inputs (44 MiB vs. 173 MiB).
Since a duplicate of this question was asked under the Python tag, here is a Python implementation of baby step, giant step, which, as #MarkBeyers points out, is a reasonable approach (as long as the modulus isn't too large):
def baby_steps_giant_steps(a,b,p,N = None):
if not N: N = 1 + int(math.sqrt(p))
#initialize baby_steps table
baby_steps = {}
baby_step = 1
for r in range(N+1):
baby_steps[baby_step] = r
baby_step = baby_step * a % p
#now take the giant steps
giant_stride = pow(a,(p-2)*N,p)
giant_step = b
for q in range(N+1):
if giant_step in baby_steps:
return q*N + baby_steps[giant_step]
else:
giant_step = giant_step * giant_stride % p
return "No Match"
In the above implementation, an explicit N can be passed to fish for a small exponent even if p is cryptographically large. It will find the exponent as long as the exponent is smaller than N**2. When N is omitted, the exponent will always be found, but not necessarily in your lifetime or with your machine's memory if p is too large.
For example, if
p = 70606432933607
a = 100001
b = 54696545758787
then 'pow(a,b,p)' evaluates to 67385023448517
and
>>> baby_steps_giant_steps(a,67385023448517,p)
54696545758787
This took about 5 seconds on my machine. For the exponent and the modulus of those sizes, I estimate (based on timing experiments) that brute force would have taken several months.
Discrete logarithm is a hard problem
Computing discrete logarithms is believed to be difficult. No
efficient general method for computing discrete logarithms on
conventional computers is known.
I will add here a simple bruteforce algorithm which tries every possible value from 1 to m and outputs a solution if it was found. Note that there may be more than one solution to the problem or zero solutions at all. This algorithm will return you the smallest possible value or -1 if it does not exist.
def bruteLog(b, c, m):
s = 1
for i in xrange(m):
s = (s * b) % m
if s == c:
return i + 1
return -1
print bruteLog(5, 8, 13)
and here you can see that 3 is in fact the solution:
print 5**3 % 13
There is a better algorithm, but because it is often asked to be implemented in programming competitions, I will just give you a link to explanation.
as said the general problem is hard. however a prcatical way to find e if and only if you know e is going to be small (like in your example) would be just to try each e from 1.
btw e==3 is the first solution to your example, and you can obviously find that in 3 steps, compare to solving the non discrete version, and naively looking for integer solutions i.e.
e = log(c + n*m)/log(b) where n is a non-negative integer
which finds e==3 in 9 steps