power and modulo on the fly for big numbers

后端 未结 3 514
春和景丽
春和景丽 2021-01-13 07:26

I raise some basis b to the power p and take the modulo m of that.

Let\'s assume b=55170 or 55172 and m=3043839241 (which happens to be the square of 55171). The li

3条回答
  •  余生分开走
    2021-01-13 08:02

    Not familiar with Scala, but...

    def powMod (b: Long, pot: Int, mod: Long) : Long = {  
          if (pot == 1) b % mod else { 
              val pot2 = pot/2 
              val pm1 = powMod (b, pot, mod)              
              val pm2 = powMod (b, pot-pot2, mod)            
              (pm1 * pm2) % mod  
          }  
    } 
    

    Did you mean

              val pm1 = powMod (b, pot2, mod) 
    

    Notice the pot2 instead of pot.

    Strangely, it seems that this should loop forever/overflow the stack, but who knows what Scala is doing.

提交回复
热议问题