您的位置 首页 编程语言

A perfect number is one that is the sum of its factors, excluding itself. The 1st perfect number is 6 because 6 = 1 + 2 + 3.

美国面试题12

 

1.题目:

A perfect number is one that is the sum of its factors, excluding itself. The 1st perfect number is 6 because 6 = 1 + 2 + 3. The 2nd perfect number is 28 which equals 1 + 2 + 4 + 7 + 14. The third is 496 = 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248. In each case, the number is the sum of all its factors excluding itself.

Write a method named henry that takes two integer arguments, i and j and returns the sum of the ith and jth perfect numbers. So for example, henry (1, 3) should return 502 because 6 is the 1st perfect number and 496 is the 3rd perfect number and 6 + 496 = 502.
The function signature is int henry (int i, int j)
You do not have to worry about integer overflow, i.e., you may assume that each sum that you have to compute can be represented as a 31 bit integer. Hint: use modulo arithmetic to determine if one number is a factor of another.

 

 

2.java 实现代码

 

public class PerfectNumber {
    public static void main(String[] args) {

//        System.out.println(getFactors(496));
        System.out.println(henry(1, 3));

    }

    public static int henry(int a, int b) {

        int count=0;
        int i =2;
        int sum =0;
        while (true){
           if( getFactors(i)!=0 ){
               count++;
               if(count==a){

                   sum = getFactors(i);
//                   return getFactors(i);

               }else if(count ==b){
                   return sum + getFactors(i);
               }
           }

            i++;

        }

    }



    /**
     * 求合数 因子
     * @param n
     * @return
     */

    public static int getFactors(int n) {

        int sum =1;

        if (n == 0)
            return 0;
        else {
//            System.out.print(1 + " ");
            for (int i = 2; i <= Math.sqrt(n); i++) {
                if (n % i == 0) {
//                    System.out.print(i + " ");
//                    System.out.print(n / i + " ");
                    sum = sum + i+ n/i;

                }
            }
//            System.out.println("sum"+sum);
            if(n == sum){
                return sum;
            }

            return 0;
        }


    }
}

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

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

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

hadoopall

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

热门文章

发表评论

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