507. Perfect Number

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)

题目含义:判断一个整数是否能由它的多个因子累加而成?

复制代码
 1     public boolean checkPerfectNumber(int num) {
 2 //        于1肯定是因子,可以提前加上,那么我们找其他因子的范围是[2, sqrt(n)]。我们遍历这之间所有的数字,如果可以被n整除,
 3 //        那么我们把i和num/i都加上,对于n如果是平方数的话,那么我们此时相同的因子加来两次,所以我们要减掉一次。
 4 //        还有就是在遍历的过程中如果累积和sum大于n了,直接返回false即可。在循环结束后,我们看sum是否和num相等
 5         if (num==1) return false;
 6         int sum=1;
 7         for (int i=2;i<Math.sqrt(num);i++)
 8         {
 9             if(num%i==0) sum += i + num/i; //找到两个因子,加到累积和sum中
10             if(num == i*i) sum -=i; //相同的因子,只加一次
11             if (sum > num) return false;
12         }
13         return sum == num;       
14     }
复制代码

 

posted @   daniel456  阅读(150)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示