您的位置 首页 编程语言

PrimeHappy

美国程序员面试题

A number n is called prime happy if there is at least one prime less than n and the sum of all primes less than n is evenly divisible by n.
Recall that a prime number is an integer > 1 which has only two integer factors, 1 and itself The function prototype is int isPrimeHappy(int n);

样例:

 

 

java 代码:

package com.zzy;

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

        System.out.println(isPrimeHappy(2));

    }
    public static int isPrimeHappy(int n ){
        if(n<=2){
            return 0;
        }


        int sum = 0;
        for (int i = 0; i < n; i++) {
            if(isPrimeNumber(i)){
                sum = sum + i;
            }

        }
        if(sum % n == 0){
            return 1;
        }
        return 0;

    }


    //判断一个数是否为素数
    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;
    }
}

猫叔总结了 适合新手操作的副业 《淘宝虚拟产品月入2万的 6个 细分类目》的电子书 仅供参考

如果你对虚拟产品比较感兴趣,可以点击:

淘宝卖什么虚拟产品赚钱(月入2万+)

hadoopall

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

热门文章

发表评论

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