![]() |
|
|
#12 |
|
Aug 2002
Portland, OR USA
27410 Posts |
Code:
//Number of bits to the right of leading ones bit. leading_zeros = leadz(n); nbits = 8*sizeof(n)-leading_zeros; // Left-justify n and shift leftmost bit off. n <<= (leading_zeros + 1); Code:
if(n == 0)
return 1;
while (n>0) n << 1;
n << 1;
r = a;
// Assumes the loop will not get executed if nbits < 1:
for(i = 1; i < nbits; i++)
{
r = (r*r)%p;
// If current (i.e. leftmost) bit = 1, multiply by a:
if(n < 0)
r = (a*r)%p;
// left-shift the exponent:
n <<= 1;
}
return r;
|
|
|
|
|
|
#13 |
|
Aug 2002
Portland, OR USA
2·137 Posts |
Here is a version of "left-to-right modular binary exponentiation" that has been kicking around the forum for quite a while.
Code:
powmod(a, b, m) {
if (b == 0) return 1;
mask = 1<<31; // can be adjusted for integer size: 1<<63
while ((b & mask) == 0) mask >>= 1;
mask >>= 1;
r = a;
while (mask) {
r = (r * r) % m;
if (b & mask) {
r = (r * a) % m;
}
mask >>= 1;
}
return r;
}
|
|
|
|
![]() |
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| (M48) NEW MERSENNE PRIME! LARGEST PRIME NUMBER DISCOVERED! | dabaichi | News | 571 | 2020-10-26 11:02 |
| Twin Prime Days, Prime Day Clusters | cuBerBruce | Puzzles | 3 | 2014-12-01 18:15 |
| disk died, prime work lost forever? where to put prime? on SSD or HDD? | emily | PrimeNet | 3 | 2013-03-01 05:49 |
| Prime Cullen Prime, Rest in Peace | hhh | Prime Cullen Prime | 4 | 2007-09-21 16:34 |
| The 40th known Mersenne prime, 220996011-1 is not PRIME! | illman-q | Miscellaneous Math | 33 | 2004-09-19 05:02 |