Subscribed unsubscribe Subscribe Subscribe

TI-Nspire & Lua / 再帰呼び出し / 階乗を求める / 普通の方法も使ってみる

f:id:ti-nspire:20170127083131p:plain:h300
.lua

----------------------------------------------
-- method 1: Calling a function recursively --
----------------------------------------------
function factorial1(n)
   if n == 0 then
      return 1 
   else 
      return n * factorial1(n - 1) 
   end
end

---------------------------------
--  method 2: Using a for loop --
---------------------------------
function factorial2(n)
   local sute = 1
   for i = 2, n do
      sute = sute * i
   end
   return sute
end

---------------------------------------------------
-- method 3: Using a built-in function of Nspire --
---------------------------------------------------
function factorial3(n)
   return math.evalStr("("..n.."!)")
end

---------------------------------------------------
---------------------------------------------------
---------------------------------------------------
num = 69
function on.paint(gc, _, _, _, h)
   local unit = math.max(6, math.min(h/15, 255))
   gc:setFont("sansserif", "r", unit) 
   gc:drawString(num.."!", 2, 0)
   gc:drawString(factorial1(num), 2, 3*unit)
   gc:drawString(factorial2(num), 2, 5*unit)
   gc:drawString(factorial3(num), 2, 7*unit)
end
Remove all ads