pow(b, n) mod m

by codeonwort
still useless for big (b, n)
♥0 | Line 29 | Modified 2011-10-21 08:57:40 | MIT License
play

ActionScript3 source code

/**
 * Copyright codeonwort ( http://wonderfl.net/user/codeonwort )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/AhDW
 */

package {
    
    import flash.text.TextFormat;
    import flash.text.TextField;
    import flash.display.Sprite;
    
    public class ModTest extends Sprite {
        
        private var tf:TextField
        
        public function ModTest() {
            // write as3 code here..
            tf = new TextField
            tf.defaultTextFormat = new TextFormat(null, 20)
            tf.autoSize = "left"
            print(5, 31, 1523)
            addChild(tf)
        }
        
        private function print(b:int, n:int, m:int):void {
            tf.text = "n = " + n + " is " + n.toString(2) + "(2)\n"
                        + "pow(" + b + ", " + n + ") mod " + m + " is " + mod(b, n, m)
        }
        
    }
    
}

// calculate pow(b, n) mod m
function mod(b:int, n:int, m:int):int {
    var binn:String = n.toString(2)
    var result:int = 1
    for(var i:int = 0 ; i < binn.length ; i++){
        if(binn.charAt(i) == '1'){
            result *= Math.pow(b, Math.pow(2, i)) % m
        }
    }
    return result % m
}