注意:Mooc提交时,不能带注释,JDK版本应该是1.8之前,因为增强for循环都不能用
题目内容:
若一个正整数的质因数分解式逐位相加之和等于其本身逐位相加之和,则称这个数为 Smith 数。如 4937775=3*5*5*65837,而 3+5+5+6+5+8+3+7=42,4+9+3+7+7+7+5=42,所以 4937775 是 Smith 数。给定一个正整数 N,求大于 N 的最小Smith 数。
输入格式:
若干个正整数,一行代表一个正整数 N,以输入 0 表示结束
输出格式:
按行输出大于正整数N 的最小 Smith 数
输入样例:
4937774
200
0
输出样例:
4937775
202
import java.util.*;
/**
* @ClassName Main
* @Description TODO:
* @Author sth_199509@163.com
* @Date 2022/5/5 12:27
* @Version 1.0
*/
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> nList = new ArrayList<Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
int n = scan.nextInt();
while(n != 0){
nList.add(n);
n = scan.nextInt();
}
for(int num : nList){
// 不包含本身,所以先给他加一
num += 1;
while(!isSmith(num)){
num++;
}
res.add(num);
}
// res.forEach(System.out::println);
for (int re : res){
System.out.println(re);
}
}
/**
* 求多位数的各个位之和
* 123返回6
* @param n
* @return
*/
public static int nSum(int n){
int res = 0;
while(n != 0){
res += n % 10;
n /= 10;
}
return res;
}
/**
* 判断是不是质数
* @param num
* @return
*/
public static boolean isPrime(int num){
if (num == 2) return true;
for (int i = 2; i < Math.sqrt(num)+1; i++) {
if(num % i == 0) return false;
}
return true;
}
/**
* 判断这个数是不是Smith数
* @param n
* @return
*/
public static boolean isSmith(int n){
int res = 0;
int target = nSum(n);
for (int i = 2; i <= n; i++) {
if(isPrime(i) && n % i == 0){
res += nSum(i);// 添加质因数的各个位之和
n /= i;// 去掉已经添加进去的,计算其他部分
i = 1;// 重置
}
}
return res == target;
}
}