我决定实现一个程序,可以在 TI-Basic 中找到任意两个数字(包括非整数)的 GCD。我已经在 Java 中很好地使用了它,所以我知道它可以工作。它在 TI-Basic 中运行良好,但与内置gcd(
功能相比,它非常缓慢;该gcd(
函数似乎在毫秒内得到结果,而我的可能需要几秒钟。为什么 TI-Basic 比预定义的计算器功能慢这么多?
编码
以下是 TI-Basic 中的程序代码,供您查看:
PROGRAM:GCD
:ClrHome
:Disp "Greatest Common"," Divisor"," ---"
:Input "First number? ",X
:Input "Second number? ",Y
:
:X→I
:Y→J
:
:If (I≠int(I) or J≠int(J))
:Then
:ClrHome
:Disp "Non-integer","inputs may be","innacurate!",""
:End
:If (I=1 or J=1)
:Then
:1→I
:1→J
:Goto Z
:End
:For(C,0,2^8)
:If I=J
:Goto Z
:
:If I>J
:I-J→I
:
:If J>I
:J-I→J
:
:End
:
:Disp "This is a hard","one! Thinking","harder..."
:
:For(C,0,2^15)
:If (I=J)
:Goto Z
:While (I>J)
:I-J→I
:C+1→C
:End
:While (J>I)
:J-I→J
:C+1→C
:End
:End
:
:Disp "TIMED OUT!","Either:",J,"or"
:Pause
:
:Lbl Z
:ClrHome
:Disp "GCD of",X,"and",Y,"is",I
免责声明:这是我查看我的 TI-84 并在此处输入的结果。可能有一些错别字,尽管我尽力保持不变
对于那些可能不知道这意味着什么的人,下面提供了伪代码:
program gcd()
{
Console.clear();
Console.writeln("Greatest Common");
Console.writeln(" Divisor");
Console.writeln(" ---");
float X = Console.readFloat("First Number? ");
float Y = Console.readFloat("Second number? ");
float I = X;
float J = Y;
if (I != (int)I || J != (int)J)
{
Console.clear();
Console.writeln("Non-integer");
Console.writeln("inputs may be");
Console.writeln("inaccurate!");
Console.writeln("");
}
if (I == 1 or J == 1)
{
I = 1;
J = 1;
goto Z;
}
for(int C = 0, limit = Math.pow(2,8); C < limit; C++)
{
if (I == J)
goto Z;
if (I > J)
I = I - J;
if (J > I)
J = J - I;
}
Console.writeln("This is a hard");
Console.writeln("one! Thinking");
Console.writeln("harder...");
for(int C = 0, limit = Math.pow(2,15); C < limit; C++)
{
if (I == J)
goto z;
while (I > J)
{
I = I - J;
C++;
}
while (J>I)
{
J = J-I;
C++;
}
}
Console.writeln("TIMED OUT!");
Console.writeln("Either:");
Console.writeln(J);
Console.writeln("or");
Console.pause();
Z:
Console.clear();
Console.writeln("GCD of");
Console.writeln(X);
Console.writeln("and");
Console.writeln(Y);
Console.writeln("is");
Console.writeln(I);
}