mersenneforum.org  

Go Back   mersenneforum.org > Great Internet Mersenne Prime Search > Math

Reply
 
Thread Tools
Old 2003-12-17, 21:16   #12
Maybeso
 
Maybeso's Avatar
 
Aug 2002
Portland, OR USA

2×137 Posts
Default

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);
So if I don't have a function leadz(), will this work instead?
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;
Maybeso is offline   Reply With Quote
Old 2003-12-18, 00:54   #13
Maybeso
 
Maybeso's Avatar
 
Aug 2002
Portland, OR USA

11216 Posts
Default

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;
}
Maybeso is offline   Reply With Quote
Reply



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

All times are UTC. The time now is 17:42.


Fri Jul 16 17:42:44 UTC 2021 up 49 days, 15:29, 1 user, load averages: 1.64, 1.49, 1.50

Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2021, Jelsoft Enterprises Ltd.

This forum has received and complied with 0 (zero) government requests for information.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation.
A copy of the license is included in the FAQ.