您的位置 首页 编程语言

largestPrimeFactor

美国程序员面试题

Write a function named largestPrimeFactor that will return the largest prime factor of a number. If the number is <=1 it should return 0. Recall that a prime number is a number > 1 that is divisible only by 1 and itself, e.g., 13 is prime but 14 is not.
The signature of the function is int largestPrimeFactor(int n)

测试样例

 

java代码实现:

package com.zzy;

/**
 * 更多请关注: http://huamaodashu.com
 * Created by huamaodashu on 27/07/2018.
 */
public class largestPrimeFactor {
    public static void main(String[] args) {

        int n=1;
        System.out.println(largestPrimeFactor(n));

    }

    public static int largestPrimeFactor (int n){
        int tmp=0;
        if(n<=1){
            return 0;
        }else {

            for (int i = 0; i < n; i++) {
                if( isPrimeNumber(i) && tmp<i && n%i==0){
                    tmp=i;

                }
            }
        }
        return tmp;
    }

    //判断一个数是否为素数
    public static boolean isPrimeNumber(int num){

        if(num == 2){
            return true;// 对2单独处理
        }
        if(num < 2 || num % 2 == 0){
            return false; // 识别小于2的数和偶数
        }
        for (int i =3; i<=Math.sqrt(num);i+=2){
            if(num % i == 0){  // 识别被奇数整除
                return false;
            }
        }
        return true;
    }

}

关于花猫大叔短视频创业 作者: hadoopall

热门文章

发表评论

电子邮件地址不会被公开。