[LeetCode] 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)
定义Perfect Number是一个正整数,它等于除了它自己之外的所有正除数的总和。现在,给定一个整数n,编写一个函数,当它是一个完美数字时返回true,否则返回false。
解法:直接解就可以。注意处理num是1的时候。还有技巧是,只计算num/2就可以,如果能整除就把除数和结果都累加。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class Solution { public boolean checkPerfectNumber( int num) { if (num == 1 ) return false ; int sum = 0 ; for ( int i = 2 ; i <= Math.sqrt(num); i++) { if (num % i == 0 ) { sum += i + num / i; } } sum++; return sum == num; } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 | class Solution( object ): def checkPerfectNumber( self , num): """ :type num: int :rtype: bool """ if num < = 0 : return False ans, SQRT = 0 , int (num * * 0.5 ) ans = sum (i + num / / i for i in range ( 1 , SQRT + 1 ) if not num % i) if num = = SQRT * * 2 : ans - = SQRT return ans - num = = num |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Solution( object ): def checkPerfectNumber( self , num): """ :type num: int :rtype: bool """ if num = = 1 : return False i = 2 s = 1 while i * i < num: if num % i = = 0 : s + = i s + = num / i i + = 1 return True if s = = num else False |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Solution { public : bool checkPerfectNumber( int num) { if (num == 1) return false ; int sum = 1; for ( int i = 2; i * i <= num; ++i) { if (num % i == 0) sum += (i + num / i); if (i * i == num) sum -= i; if (sum > num) return false ; } return sum == num; } }; |
C++:
1 2 3 4 5 6 | class Solution { public : bool checkPerfectNumber( int num) { return num==6 || num==28 || num==496 || num==8128 || num==33550336; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构