ユークリッドの互除法
import Prelude hiding (gcd)
gcd :: Int -> Int -> Int
gcd m n
| m < n = gcd n m
| m `mod` n == 0 = n
| otherwise = gcd n (m `mod` n)
Main> gcd 7 5
1
Main> gcd 12 18
6
Main>
○ Exercise 4.14
power2 :: Int -> Int
power2 n
| n == 0 = 1
| n == 1 = 2
| n `mod` 2 == 0 = square (power2 (n `div` 2))
| otherwise = 2 * square (power2 ((n-1) `div` 2))
where square x = x * x
Main> power2 0
1
Main> power2 1
2
Main> power2 2
4
Main> power2 3
8
Main> power2 4
16
Main> power2 5
32
Main>
No comments:
Post a Comment