题解 | #最大公约数#

质数因子

http://www.nowcoder.com/practice/196534628ca6490ebce2e336b47b3607

// 判断数字是否为质数,改进用根号降低时间复杂度
import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ArrayList<Integer> arr = new ArrayList<Integer>();
        get(arr,n);
        if(arr.size() == 0)
            arr.add(n);
        for(int i = 0;i < arr.size();i++){
            System.out.print(arr.get(i)+" ");
        }
    }
    public static void get(ArrayList<Integer> arr,int n) {
        // extern condition:identiy is zhi number
        if(isNumber(n)){
            arr.add(n);
            return;
        } 
        for(int i=2;i<=Math.sqrt(n);i++){
            if(n % i == 0){
                n = n / i;
                arr.add(i);
                break;
            }
        }
        get(arr,n);
    }
    public static boolean isNumber(int n) {
        for(int i = 2;i<=Math.sqrt(n);i++){
            if(n % i == 0)
                return false;
        }
        return true;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 18:25
点赞 评论 收藏
分享
06-18 13:28
已编辑
门头沟学院 Web前端
爱睡觉的冰箱哥:《给予你300的工资》,阴的没边了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务