之前没有发现这是一本C语言编写得书,但本人还未学习过C语言,只能尝试用java实现书中的代码,在此记录学习这本书的历程。
本人新手菜鸟,能力有限,如果有误或者有改进的地方欢迎指出,谢谢\(▔▽▔)/。
题目:如果x加上x的各个数字之和得到y,就说x是y的生成元。给出n(1<= n <= 100000),求最小生成元。无解输出0.例如,n=216,121,2005时的解为198,0,1979.
代码:
//将范围内的所有最小生成元全部找出
//并将生成元与数字之间通过数组的索引与存储的关系联系起来,避免使用两个数组。
public static void main(String args[]) {
int []check = new int[100045];
for(int i = 1;i < 100000;i++) { //生成查询表
int a = i;
int count = a;
while(a%10 > 0) {
count += a%10;
a /= 10;
}
//确保是最小生成元
if(check[count] == 0 ||check[count] > i) {
check[count] = i;
}
}
Scanner input = new Scanner(System.in);
while(input.hasNextInt()) {
int numbers = input.nextInt();
if(check[numbers] != 0) {
System.out.println(check[numbers]);
}else {
System.out.println(0);
}
}
}