PowerShell:98
ゴルフコード:
for($a,$b=0,(1%($n=read-host))){$x++;if($a+$b-eq0-or("$a$b"-eq10)){$x;break}$a,$b=$b,(($a+$b)%$n)}
Ungolfed、コメント付き:
for
(
# Start with $a as zero, and $b as 1%$n.
# Setting $b like this at the start helps catch the exceptional case where $n=1.
$a,$b=0,(1%
(
# Grab user input for n.
$n=read-host
))
)
{
# Increasing the counter ($x) and testing for the end of the period at the start ensures proper output for $n=1.
$x++;
# Test to see if we've found the end of the Pisano Period.
if
(
# The first part catches $n=1, since $a and $b will both be zero at this point.
$a+$b-eq0-or
(
# A shorter way of testing $a-eq1-and$b-eq0, which is the end of a "normal" Pisano Period.
"$a$b"-eq10
)
)
{
# Pisano Period has reached its end. Output $x and get out of the loop.
$x;break
}
# Pisano Period still continues, perform operation to calculate next number.
# Works pretty much like a Fibonacci sequence, but uses ($a+$b)%$n for the new $b instead.
# This takes advantage of the fact we don't really need to track the actual Fibonacci numbers, just the Fibonacci pattern of %$n.
$a,$b=$b,(($a+$b)%$n)
}
# Variable cleanup - not included in golfed code.
rv n,a,b,x
ノート:
このスクリプトでの$ nの信頼できる最大制限は正確にはわかりません。$ nが到達する前に$ xがint32をオーバーフローさせる可能性があるため、2 ^ 30未満の可能性があります。それに加えて、システムの$ n = 1e7(2 ^ 23を少し超える)でスクリプトの実行時間が約30秒に達するため、上限を自分でテストしていません。同じ理由で、このスクリプトの範囲を拡張するために、必要に応じて変数をuint32、int64、またはuint64にアップグレードするために必要な追加構文があれば、すぐにテストおよびトラブルシューティングを行うつもりはありません。
サンプル出力:
これを別のforループでラップしました。
for($i=1;;$i++)
次に、の$n=$i
代わりに設定し=read-host
、出力を"$i | $x"
に変更して、スクリプトの一般的な信頼性を把握します。出力の一部を次に示します。
1 | 1
2 | 3
3 | 8
4 | 6
5 | 20
6 | 24
7 | 16
8 | 12
9 | 24
10 | 60
11 | 10
12 | 24
13 | 28
14 | 48
15 | 40
16 | 24
17 | 36
18 | 24
19 | 18
20 | 60
...
9990 | 6840
9991 | 10192
9992 | 624
9993 | 4440
9994 | 1584
9995 | 6660
9996 | 1008
9997 | 1344
9998 | 4998
9999 | 600
10000 | 15000
10001 | 10212
10002 | 3336
10003 | 5712
10004 | 120
10005 | 1680
10006 | 10008
10007 | 20016
10008 | 552
10009 | 3336
10010 | 1680
補足: Pisano Periodsが$ nよりも大幅に短いかどうかはよくわかりません。これは正常ですか、それともスクリプトに問題がありますか?ネバーマインド-5の後、フィボナッチ数がシーケンスの位置よりもはるかに大きくなることを思い出しました。したがって、これは今では完全に理にかなっています。