java笔试之完全数计算
2024-09-06 11:32:56
完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数。
它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。
例如:28,它有约数1、2、4、7、14、28,除去它本身28外,其余5个数相加,1+2+4+7+14=28。
给定函数count(int n),用于计算n以内(含n)完全数的个数。计算范围, 0 < n <= 500000
返回n以内完全数的个数。异常情况返回-1
注意:为降低时间复杂度,从2到n的开方遍历。
package test; import java.util.Scanner; //完美数
public class exam08 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int num = scanner.nextInt();
System.out.println(count(num)); }
} public static Boolean isPerfect(int i) {
boolean isperfect = false;
int sum = 0;
for (int j = 1; j <= Math.sqrt(i); j++) {
// 开方,降低时间复杂度
// 注意要加上另外一个对应的约数
if (i % j == 0) {
sum += j + i / j;
}
}
if ((sum - i) == i) {
isperfect = true;
}
return isperfect;
} public static int count(int n) {
int sum = 0;// 完美数个数
if (n >= 0) {
// 完美数不包括1
for (int i = 2; i <= n; i++) {
if (isPerfect(i)) {
// System.out.println(i);
sum++;
}
}
} else {
sum = -1;
}
return sum;
}
}
最新文章
- 安卓手机 虚拟键盘输入用 position:fixed解决 !!!
- JSON resource 启示
- iOS 从应用中跳转至系统设置页面里的多种设置页面
- struts2的核心和工作原理
- generator自动生成mybatis配置和类信息
- [翻译]利用REDIS来搭建可靠分布式锁的提议
- 不使用容器构建Registry
- Nuget 摘录
- 关于ios中的文本操作-简介
- mysql启动报错:Fatal error: Can’t open and lock privilege tables: Table ‘mysql.host’ doesn’t exist
- uptime
- c#中,委托Func的简单实践
- 1677: [Usaco2005 Jan]Sumsets 求和
- cookie和session的区别异同
- 11) 十分钟学会android--Intent消息处理与传递详解
- xadmin 数据添加报错: IndexError: list index out of range
- c++模板参数——数值类型推断
- jquery.qrcode.js 生成二维码并支持中文的方法
- 如何将docker镜像文件上传至Docker Hub
- centos安装tree命令
热门文章
- 【优化】碎片OPTIMIZE
- [Android开发常见问题-4] RunTime.exec()如何以root权限执行多条指令?
- (转)The connection to adb is down, and a severe error has occured. .
- APC注入DLL(win7下有问题)
- 用solr DIH 实现mysql 数据定时,增量同步到solr
- Function(高阶函数式编程)
- 蒟蒻kc的垃圾数列
- Milking Cows /// 区间计数 离散化排序 oj10105
- C++ vector操作--往列表中添加或更新内容
- JS事件 内容选中事件(onselect)选中事件,当文本框或者文本域中的文字被选中时,触发onselect事件,同时调用的程序就会被执行。