43:质因数分解

一、题目链接

http://noi.openjudge.cn/ch0105/43/

二、解题思路

◎ 根据质因数分解的唯一性,用给定整数n去除从2开始的每个数k,如果能除尽,则n/k就是n的较大质因数。

三、实施步骤

◆ 方法public int greaterPrime(int n)处理所有业务逻辑:
   → 参数n为int类型的整数,代表给定整数;
   → 方法greaterPrime返回int类型的整数,代表n的较大质因数。
◇ 方法greaterPrime实施步骤如下:
◎ 首先,定义int类型的整数smallerPrime,代表较小的质因数;
◎ 其次,在n%smallerPrime!=0时,循环处理如下:
   → 令smallerPrime++;
◎ 最后,返回n/smallerPrime。
◇ 在方法main中输入给定整数n,将其作为参数注入方法greaterPrime,输出计算结果。

四、Java程序

import java.util.Scanner;

public class Main {
    /**
     * 计算给定整数的较大质因数
     *
     * @param n int类型的整数,代表给定整数
     * @return int类型的整数,代表n的较大质因数
     */
    public int greaterPrime(int n) {
        int smallerPrime = 2; // 较小的质因数从2开始
        /* 在smallerPrime不是n的因数时 */
        while (n % smallerPrime != 0) {
            smallerPrime++; // 令smallerPrime加1
        }
        return n / smallerPrime; // 返回较大的质因数
    }

    public static void main(String[] args) {
        Main test = new Main();
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        System.out.print(test.greaterPrime(n));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江苏科技大学_计算机学院_潘磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值