ç´¯ä¹(x^n)ãåç´ã«è¨ç®ããã¨ããªã¼ãã¼ã¯ O(n)ã¨ãªãå¹çãæªãã§ããããã§ãnã2ã®ç´¯ä¹ã«å解ãã¦è¨ç®ããé«éåææ³ãä¸è¬ã«ç¥ããã¦ãã¾ãã
ãã¨ãã°ã3 ã® 11 ä¹ãè¨ç®ããå ´åãèãã¾ãããã11 㯠1 + 2 + 8 ã«å解ã§ãã¾ãã
ãã®ç´¯ä¹ã®ç³»åã§ã¯ãããå¤ã¯ä¸ã¤åã®å¤ã2ä¹ãããã¨ã§è¨ç®ã§ãã¾ãããã¨ãã°ãããã§ãã
3^1 = 3 3^2 = 3 * 3 = 9 3^4 = (3^2)^2 = 9^2 = 81 3^8 = (3^4)^2 = 81^2 = 6561
ãã£ã¦ã3^11 ã¯ä»¥ä¸ã®ããã«è¨ç®ã§ãã¾ãã
3^11 = 3^(1+2+8) = 3^1 Ã 3^2 Ã 3^8 = 3 Ã 9 Ã 6561 = 177147
ãã®æ¹æ³ã®ãªã¼ãã¼ã¯ãO(log2(n)) ã§ãã
é 延è©ä¾¡é¢¨ã«
RSA のために高速な累乗計算を Haskell で実装したãã¨ãããã¾ããããã®ã¨ãã®ã³ã¼ãã¯ããããªæãã§ãã
import Data.Bits power x n = iter n seq 1 where seq = iterate (\y -> y*y) x iter 0 _ ret = ret iter b (s:ss) ret = let next = if odd b then ret * s else ret in iter (shiftR b 1) ss next
é 延è©ä¾¡ãçããã¦ãx ã2ä¹ã2ä¹ã¨ä¹ãã¦ããç¡éæ°å(seq)ãä½ã£ã¦ããã¨ããããã¤ã³ãã§ãã
ãã®ã³ã¼ãã¯ã¡ããã¨åãã¾ãããå³ã·ãã(shiftR)ã使ã£ã¦ããã®ã§ãããµããªãã¨æã£ã¦ãã¾ããã(ããã`mod` 2 ã使ã£ã¦ããããã§ãããããã§ãããµãã§ããã)
ç¾ããã¢ã«ã´ãªãºã
ç¾å¨è¼ªè¬ã§èªãã§ãã SOE ã«ãç´¯ä¹ãé«éã«è¨ç®ã§ãããããç¾ããã¢ã«ã´ãªãºã ãè¼ã£ã¦ãã¾ãããããã¯ãããã§ãã
power x n | n == 0 = 1 | even n = power (x*x) (n `div` 2) | otherwise = x * power x (n - 1)
åããã¾ããï¼
- å¶æ°ã®ã¨ãã¯ãçµæã¯å¤ããããx ã 2 ä¹ããn ãååã«ãã
- x^6 = (x^2)^3
- åºæ°ã®ã¨ãã¯ãçµæã« x ãæããï½ã¯ãã®ã¾ã¾ã§ãn ãä¸ã¤æ¸ãã
- x^7 = x à x^6
ãããç解ã§ããã°ãã¢ã«ã´ãªãºã ãæ£ããã®ã¯æããã§ãã
ãªã¼ãã¼ã¯ O(log2(n)) ã§ãããªããªããn ãå¥æ°ã®ã¨ãã¯ã1ãå¼ãã®ã§ã次ã¯å¿ ãå¶æ°ã«ãn ãå¶æ°ã®ã¨ãã¯ãååã«ãã¦ã次ã¯å¶æ°ãå¥æ°ã«ãã¨ãã訳ã§ãæä½ã§ã2åã«ä¸åã¯ãn ã®ãããæ°ãæ¸ãã®ã§ãã
ç¾ãããªããæåããï¼
The Haskell School of Expression: Learning Functional Programming through Multimedia
- ä½è : Professor Paul Hudak
- åºç社/ã¡ã¼ã«ã¼: Cambridge University Press
- çºå£²æ¥: 2000/06
- ã¡ãã£ã¢: ãã¼ãã¼ããã¯
- è³¼å ¥: 2人 ã¯ãªãã¯: 27å
- ãã®ååãå«ãããã° (16件) ãè¦ã