Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Add fully working but not terribly optimized versions of infix:<gcd> …
…and infix:<lcm>.
  • Loading branch information
colomon committed Oct 28, 2011
1 parent f5dc966 commit 5ec4d8d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/Builtins.cs
Expand Up @@ -960,6 +960,19 @@ public partial class Builtins {
return Kernel.NewROScalar(n1);
}

static readonly Func<Variable,Variable,Variable> gcd_d = gcd;
public static Variable gcd(Variable a1, Variable a2) {
int r1, r2;
P6any o1 = a1.Fetch(), o2 = a2.Fetch();
if (!(o1.mo.is_any && o2.mo.is_any))
return HandleSpecial2(a1,a2, o1,o2, minus_d);
P6any n1 = GetNumber(a1, o1, out r1);
P6any n2 = GetNumber(a2, o2, out r2);

// SHOULD: optimize for the case of two small sized Ints
return MakeInt(BigInteger.GreatestCommonDivisor(PromoteToBigInt(r1, n1), PromoteToBigInt(r2, n2)));
}

[TrueGlobal] static IForeignInterpreter p5_interpreter;
public static Variable eval_perl5(Variable v) {
P6any o1 = v.Fetch();
Expand Down
8 changes: 8 additions & 0 deletions lib/CORE.setting
Expand Up @@ -22,6 +22,14 @@ sub infix:</> is Niecza::builtin('divide',2,2) is equiv<*> ($l,$r) { $l / $r }
sub infix:<%> is Niecza::builtin('mod',2,2) is equiv<*> ($l,$r) { $l % $r }
sub infix:<**> is Niecza::builtin('pow',2,2) is Niecza::absprec<w=> is assoc<right> ($l,$r) { $l ** $r }

# sub infix:<gcd>($l,$r) is Niecza::builtin('gcd',2,2) { $l gcd $r }
sub infix:<gcd>($l,$r) { Q:CgOp { (gcd {$l.Int} {$r.Int}) } }
sub infix:<lcm>($l,$r) {
my $l-int = $l.Int.abs;
my $r-int = $r.Int.abs;
$l-int div ($l-int gcd $r-int) * $r-int;
}

sub next ($x?) { _lexotic(1, $x, ()) }
sub last ($x?) { _lexotic(2, $x, ()) }
sub redo ($x?) { _lexotic(3, $x, ()) }
Expand Down

0 comments on commit 5ec4d8d

Please sign in to comment.