From d58154ad35ab1e0b0d9d520419b08fe8565b7b2c Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Sat, 16 Sep 2023 18:05:52 -0400 Subject: factorial function --- func.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'func.go') diff --git a/func.go b/func.go index fee20da..42763c0 100644 --- a/func.go +++ b/func.go @@ -16,6 +16,8 @@ func parseFunction(fn string) func(Calculator) { return deg case "rad": return rad + case "fac": + return fac } return nil } @@ -69,18 +71,36 @@ func invTrig(fn string) func(Calculator) { } } +// Convert radians to degrees. func deg(c Calculator) { if len(c.stack) > 0 { c.stack[len(c.stack)-1] = degrees(c.stack[len(c.stack)-1]) } } +// Convert degrees to radians. func rad(c Calculator) { if len(c.stack) > 0 { c.stack[len(c.stack)-1] = radians(c.stack[len(c.stack)-1]) } } +// Factorial (!). +func fac(c Calculator) { + if len(c.stack) > 0 { + a := &c.stack[len(c.stack)-1] // will replace with a! + if float64(int(*a)) != *a { // undefined on non-ints + return + } else if int(*a) == 0 { // 0! = 1 + *a = 1.0 + } else { // a! = a*(a-1)! + for i := int(*a) - 1; i > 1; i-- { + *a *= float64(i) + } + } + } +} + // radians converts degrees to radians. func radians(deg float64) float64 { return deg * math.Pi / 180.0 -- cgit v1.2.3