Pascal 大模算法
我正在尝试为我的学校编程团队的在线评委制作一个Pascal程序。程序必须输出a^b mod c,其中a、b和c作为输入。您不能使用暴力作为测试用例,因为所有测试用例都有非常大的数字 经过一些研究,我发现我可以使用分而治之的策略。这是我想出的代码:Pascal 大模算法,pascal,divide-and-conquer,Pascal,Divide And Conquer,我正在尝试为我的学校编程团队的在线评委制作一个Pascal程序。程序必须输出a^b mod c,其中a、b和c作为输入。您不能使用暴力作为测试用例,因为所有测试用例都有非常大的数字 经过一些研究,我发现我可以使用分而治之的策略。这是我想出的代码: function pmod(a,b,c:longint):integer; begin if b = 0 then pmod := 1; if b = 1 then pmod := a mod c;
function pmod(a,b,c:longint):integer;
begin
if b = 0 then
pmod := 1;
if b = 1 then
pmod := a mod c;
if b > 1 then
begin
if (b mod 2) = 0 then
pmod := (pmod(a,b div 2,c) * pmod(a,b div 2,c)) mod c
else
pmod := (pmod(a,b-1,c) * (a mod c)) mod c;
end;
end;
然而,在线法官给出了错误的答案。有人能指出代码有什么问题吗?您的算法基本上是正确的,应该可以工作。你的代码中肯定有一些小地方可以改进,但我不会说它是“错的”。让我们看看一些可能的问题
function pmod(a,b: int64; c:integer):integer;
var tmp: int64;
begin
if b < 0 then pmod := -1; {flag an error}
if b = 0 then pmod := 1;
if b = 1 then pmod := a mod c;
if b > 1 then
begin
if (b mod 2) = 0 then
begin
tmp :=pmod(a,b div 2,c) * pmod(a,b div 2,c);
pmod := tmp mod c
end
else
begin
tmp := pmod(a,b-1,c) * (a mod c);
pmod := tmp mod c
end
end;
end;