1年前 (2018-08-13)  编程语言 |   抢沙发  25 
文章评分 0 次,平均分 0.0

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://hadoopall.com
 * Created by hadoopall 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;
    }
}
 

除特别注明外,本站所有文章均为HadoopAll原创,转载请注明出处来自http://hadoopall.com/592.html

发表评论

表情 格式

暂无评论

登录

忘记密码 ?

切换登录

注册

扫一扫二维码分享