Smith数问题【Java】

注意: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;
    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值