AOJ本の読書メモ
AOJ
次のAOJの問題へ
前のAOJの問題へ
NTL_1_B: Power
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
// Q084 ModPow https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=NTL_1_B&lang=jp
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("2 3");
//8
}
else if (InputPattern == "Input2") {
WillReturn.Add("5 8");
//390625
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
long[] wkArr = InputList[0].Split(' ').Select(pX => long.Parse(pX)).ToArray();
long m = wkArr[0];
long n = wkArr[1];
const long Hou = 1000000007;
long Result = DeriveModPow(m, n, Hou);
Console.WriteLine(Result);
}
//繰り返し2乗法で、(NのP乗) Mod Mを求める
static long DeriveModPow(long pN, long pP, long pM)
{
long CurrJyousuu = pN % pM;
long CurrShisuu = 1;
long WillReturn = 1;
while (true) {
//対象ビットが立っている場合
if ((pP & CurrShisuu) > 0) {
WillReturn = (WillReturn * CurrJyousuu) % pM;
}
CurrShisuu *= 2;
if (CurrShisuu > pP) return WillReturn;
CurrJyousuu = (CurrJyousuu * CurrJyousuu) % pM;
}
}
}
解説
繰り返し2乗法を使ってます。