題目連結
題意:
一個4位數字的亂數產生器
給定一個初始值 a0
產生的方法是先平方,將結果補齊到8位數字
取中間的4位即為新產生的數字
重複動作,計算總共可以產生多少不同的數字
例如:
解法:
重複執行上述動作,每找到新的數字就令次數 +1
用一個陣列表示數字找到與否,若已經找過則停止
因為同一個輸入,必會產生相同的新數字 (都是平方取中間)
題目要計算多少不同的數字
已經找過則表示後續會形成循環,而不必做下去
程式(Java):
題意:
一個4位數字的亂數產生器
給定一個初始值 a0
產生的方法是先平方,將結果補齊到8位數字
取中間的4位即為新產生的數字
重複動作,計算總共可以產生多少不同的數字
例如:
解法:
重複執行上述動作,每找到新的數字就令次數 +1
用一個陣列表示數字找到與否,若已經找過則停止
因為同一個輸入,必會產生相同的新數字 (都是平方取中間)
題目要計算多少不同的數字
已經找過則表示後續會形成循環,而不必做下去
程式(Java):
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 java.util.*; | |
public class Main { | |
public static void main(String args[]) { | |
Scanner sc = new Scanner(System.in); | |
while (sc.hasNext()) { | |
int a0 = sc.nextInt(); | |
if (a0 == 0) | |
break; | |
int count = 0; | |
boolean check[] = new boolean[10001]; | |
while (!check[a0]) { | |
count++; | |
check[a0] = true; | |
a0 *= a0; | |
a0 /= 100; | |
a0 %= 10000; | |
} | |
System.out.println(count); | |
} | |
} | |
} |
留言
張貼留言