This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import System.Environment | |
import Data.List | |
getNs :: IO [Integer] | |
getNs = getArgs >>= mapM (return . read) | |
f 2 x = x * 2 + 1 | |
f 3 x = x ^ 2 * 3 + x * 3 + 1 | |
next g l m = | |
if null t then (0,0) | |
else (last t, genericLength t) | |
where t = takeWhile (<= l) $ scanl1 (+) $ map (f m) [g..] | |
iPart i n m = let (r,d) = next i n m in return (d+1) | |
loop c g l m root = do | |
let (r,d) = next g l m | |
putStr $ show d | |
let nr = newroot d | |
loop (c+1)(nr*10) ((l - r) * 10 ^ m) m nr | |
where newroot d = root*10+d | |
main = do | |
n:m:[] <- getNs | |
r <- iPart 1 n m | |
print r | |
if r ^ m == n | |
then print () | |
else loop 1 (r * 10) ((n-r^m)*10^m) m r |
2の平方根
$ runghc nroot.hs 2 2 | tee a
2の立方根
$ runghc nroot.hs 2 3 | tee b
猛列な勢いで計算しますので適当なファイルに保存もしています。(Ctrl-Cで停止)
なお√2に限ればこう書けます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
loop a b n = do | |
let c = a*2+1 | |
if c<b then loop (a+1)(b-c)(n+1) | |
else putStr (show n) >> loop (a*10)(b*100)0 | |
main = loop 1 1 1 |
One liner:
loop a b n = return (a*2+1) >>= \c -> if c<b then loop (a+1)(b-c)(n+1) else putStr (show n) >> loop (a*10)(b*100)0; main = loop 1 1 1
平方根は正方形の色紙を百分割して並べることで、
立方根は正四角形のサイコロを千分割して貼り付けていくことで深い桁まで計算をすすめることができます。
参照ページ
http://senjounosantafe.blogspot.com/2018/05/2.html
0 件のコメント:
コメントを投稿