博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Perfect Number
阅读量:4099 次
发布时间:2019-05-25

本文共 1231 字,大约阅读时间需要 4 分钟。

题目地址:

We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.

Example:

Input: 28

Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14

Note: The input number n will not exceed 100,000,000. (1e8)

找出所有的质数,然后累加,累加结果等于原来的数字返回true,否则返回false

计算所有的质数不必从1到num遍历一次,只遍历到 num 即可。

public class PerfectNumber {
public static boolean checkPerfectNumber(int num) { if (num <= 1) return false; int sum = 1; int s = (int)Math.sqrt(num); //以免加两次平方根,例如Math.sqrt(9) = 3,但是3只应该出现一次。 boolean bol = (num / s == 0) && (s == (num / s)); for (int i = 2; i <= s; i++) { if (num % i == 0) { if (i == s && bol) sum = sum + i; else sum = sum + i + num / i; } } if (sum == num) return true; return false; } public static void main(String[] args) { for (int i = 1; i < 10000; i++) { if (checkPerfectNumber(i)) { System.out.println(i); } } }}

转载地址:http://uihii.baihongyu.com/

你可能感兴趣的文章
《python+opencv实践》四、图像特征提取与描述——31 Shi-Tomasi 角点检测& 适合于跟踪的图像特征
查看>>
OpenCV meanshift目标跟踪总结
查看>>
人工神经网络——神经元模型介绍
查看>>
人工神经网络——感知器介绍
查看>>
人工神经网络——反向传播算法(BackPropagation)
查看>>
进程的地址空间概述
查看>>
Windows 窗口底层原理
查看>>
一种函数指针的运用
查看>>
Win32程序之进程的原理
查看>>
C++虚函数原理
查看>>
MySQL的索引
查看>>
今天,Python信息量很大!
查看>>
Flash 已死,Deno 当立?
查看>>
编程差的程序员,90%都是吃了数学的亏!骨灰级开发:方法不对,努力也白费...
查看>>
编程差的程序员,90%都是吃了数学的亏!骨灰级开发:方法不对,努力也白费...
查看>>
都无代码了,还要程序员吗?
查看>>
程序员:凭自己能力吃饭,有什么理由瞧不起?
查看>>
面试想拿 10K,HR 说我只配7k?
查看>>
副业过万的程序员都知道的网站有哪些
查看>>
那些人生“开挂”的程序员,都在干什么?
查看>>