力扣507题---完美数
对于一个正整数,如果它和除了它自身以外的所有 正因子之和相等,我们称它为「完美数」。
给定一个整数n,如果是完美数,返回true;否则返回false。
示例 1:输入:num = 28 输出:true
解释:28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, 和 14 是 28 的所有正因子。
示例 2:输入:num = 7 输出:false
提示:1 <= num <= 10^8。
方法代码:
- class Solution {
- public boolean checkPerfectNumber(int num) {
- if (num == 1) {
- return false;
- }
- int sum = 1;
- for (int n = 2; n * n <= num; n++) {
- if (num % n == 0) {
- sum += n;
- if (n * n < num) {
- sum += num / n;
- }
- }
- }
- return sum == num;
- }
- }
实例测试(打印出所有的完美数):
- import java.util.Scanner;
-
- public class Main {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- for (int i = 1; i <= n; i++) {
- if (checkPerfectNumber(i)) {
- System.out.println(i);
- }
- }
- }
-
- public static boolean checkPerfectNumber(int num) {
- if (num == 1) {
- return false;
- }
- int sum = 1;
- for (int n = 2; n * n <= num; n++) {
- if (num % n == 0) {
- sum += n;
- if (n * n < num) {
- sum += num / n;
- }
- }
- }
- return sum == num;
- }
- }
输入:1000
输出:
6
28
496
实例测试(打印出所有的完美数及它们的因数):
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.Scanner;
-
- public class Main {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- for (int i = 4; i <= n; i++) {
- getFactors(i);
- }
- }
-
- private static void getFactors(int n) {
- int sum = 0;
- List list1 = new ArrayList();
- list1.add(1);
- for (int i = 2; i <= Math.sqrt(n); i++) {
- if (n % i == 0) {
- list1.add(i);
- if (n != i * i) {
- list1.add(n / i);
- }
- }
- }
- Collections.sort(list1);
- for (int j = 0; j < list1.size(); j++) {
- sum = sum + (int) list1.get(j);
- }
- if (sum == n) {
- System.out.println(n + "的因数有:" + list1);
- }
- }
- }
输入:1000
输出:
6的因数有:[1, 2, 3]
28的因数有:[1, 2, 4, 7, 14]
496的因数有:[1, 2, 4, 8, 16, 31, 62, 124, 248]