【PTA】L1-006 连续因子

https://pintia.cn/problem-sets/994805046380707840/problems/994805138600869888

解析

求一个整数 N 的最长连续因子,且它是最小的,不包含 1。

那么我们从 2 开始逐个去与 N 取模,判断 j 是否为 N 的因子,注意这个过程是连续的,若期间 N % j ≠ 0 N \% j \neq 0 N%j=0 ,则就终止,期间要记录和更新连续的长度 temp,还需要注意因子连续的乘积也必须为 N 的因子。

若真的从 2 开始逐个求因子,那么必然会 TLE,因此到 s q r t ( N ) sqrt(N) sqrt(N) 结束即可,(别问我为什么,我也不知道)。

而判断因子,我们只需要判断到 s q r t ( N ) sqrt(N) sqrt(N) 即可(这个不用我说,都知道)。

AC Code

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StreamTokenizer st = new StreamTokenizer(br);
    static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

    public static void main(String[] args) throws Exception {
        int n = nextInt();
        int sqrt = (int) Math.sqrt(n);
        int start = 0, len = 0;
        for(int i = 2; i <= sqrt; i++) { // 以 i 打头
            int temp = 0; // 连续因子的长度
            int cur = 1; // 连续因子的乘积
            for(int j = i; j <= n / i; j++) { // 判断因子
                if(n % j == 1) break; // 不是因子,直接退出
                if(n % (cur * j) == 0) { // 乘积也需要为 N 的因子
                    temp++;
                    cur *= j;
                } else break;
            }
            if(temp > len) { // 只要长度最长的因子
                start = i; // 记录起始位置
                len = temp; // 更新长度
            }
        }

        if(start == 0) { // 是质数
            System.out.println(1);
            System.out.println(n);
            return;
        }

        System.out.println(len);

        for(int i = start; i < start + len; i++) {
            if(i != start + len - 1) System.out.print(i + "*");
            else System.out.print(i);
        }
    }

    public static int nextInt() throws Exception {
        st.nextToken();
        return (int) st.nval;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值