本文共 2006 字,大约阅读时间需要 6 分钟。
为了解决这个问题,我们需要找出卡拉兹猜想中的关键数。关键数是那些在递推过程中无法被其他数字所覆盖的数。也就是说,如果一个数在递推过程中被另一个数生成,那么它就不是关键数。
import java.util.ArrayList;import java.util.Collections;import java.util.List;public class Test1005Continue3nPlusOne { public static void main(String[] args) { Scanner ss = new Scanner(System.in); int K = Integer.parseInt(ss.nextLine()); List nList = new ArrayList<>(); for (int i = 0; i < K; i++) { nList.add(Integer.parseInt(ss.nextLine())); } // 生成递推序列 List > sequences = new ArrayList<>(); for (int num : nList) { List sequence = new ArrayList<>(); int a = num; while (a != 1) { sequence.add(a); if (a % 2 == 0) { a = a / 2; } else { a = (3 * a + 1) / 2; } } sequence.add(1); // 添加终止条件 sequences.add(sequence); } // 判断每个数是否是关键数 List keys = new ArrayList<>(); for (int num : nList) { boolean isKey = true; for (int other : nList) { if (other == num) continue; if (sequences.get(other).contains(num)) { isKey = false; break; } } if (isKey) { keys.add(num); } } // 按从大到小排序并输出 Collections.sort(keys, (a, b) -> b.compareTo(a)); System.out.print(keys.get(0)); for (int i = 1; i < keys.size(); i++) { System.out.print(" " + keys.get(i)); } }}
这种方法确保了我们能够高效地找出所有关键数,并按要求输出。
转载地址:http://fcnbz.baihongyu.com/