美国程序员面试题
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;
}
}