Greatest Common Denominator Procedures
|
|
The following are two procedures to calculate the greatest common denominator(GCD) of two numbers. The reason I'm listing two procedures instead of one is because my benchmark results of them prove their runtimes are the same in a sense. Considering the ternary procedure is pretty much the exact same as the basic procedure it makes sense for them to come up as the faster/slower than each other depending on the runtimes.
Syntaxs:
Basic_GCD(number1,number2)
Ternary_GCD(number1,number2)
Code:
//Basic proc Basic_GCD(num1 as num,num2 as num) if(!num2) return num1 return Recursive_GCD(num2, num1%num2)
//Ternary proc Ternary_GCD(num1 as num,num2 as num) return !num2 ? num1 : Recursive_Ternary_GCD(num2, num1%num2)
How to use:
mob/verb/GCD() var number1=3000, number2 = 3 world << Basic_GCD(number1,number2) world << Ternary_GCD(number1,number2)
Output:
|
Example: 42 and 13. 13 and 5.
The problem comes from your line here
return num1%num2
Normally, I'd do a check for even/odd. Even numbers can be based on powers of 2, and I'd reduce odd numbers to even numbers and solve the problem above.
A brute force method could also be employed, where you check every integer between 0 and the smaller number to see if it divides the larger number.