A hodder number is one that is prime and is equal to 2j-1 for some j. For example, 31 is a hodder number because 31 is prime and is equal to 25-1 (in this case j = 5). The first 4 hodder numbers are 3, 7, 31, 127
Write a function with signature int isHodder(int n) that returns 1 if n is a hodder number, otherwise it returns 0.
Recall that a prime number is a whole number greater than 1 that has only two whole number factors, itself and 1.
java实现代码:
package com.zzy;
/**
* 更多请关注: http://huamaodashu.com
* Created by huamaodashu on 13/08/2018.
*/
public class HodderNumber {
public static void main(String[] args) {
System.out.println(isHodder(122));
}
public static int isHodder(int n ){
if(!isPrimeNumber(n)){
return 0;
}
for (int i = 0; i <= (int)Math.sqrt(n)+1; i++) {
// System.out.println((double)Math.sqrt(n));
if(Math.pow(2,i)-1 == n){
return 1;
}
}
return 0;
}
//判断一个数是否为素数 只能被1 和本身整除 . 3
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;
}
}