Test question:
If a number is exactly equal to the sum of its factors, the number is called a perfect number. Example 6=1+23. Program to find all perfect numbers within 1000.
(Learning video sharing: java teaching video)
Idea:
for loop, Assign i a value of 1~1000
Find the numbers that can divide i and add them
After adding If the sum of the numbers is equal to i, then output i
Implementation code:
package com.thz.hnstc.test01; /* * @author NanTang * */ public class PerfectNumber { public static void main(String[] args) { for (int i = 1; i < 1000; i++) { int sum = 0; for (int j = 1; j < i; j++) { if(i % j == 0) sum += j; } if(sum == i) System.out.println("完数:" + i); } } }
Running result:
完数:6 完数:28 完数:496
Related recommendations: Java introductory tutorial
The above is the detailed content of Java small test seeks to complete the number within 1000. For more information, please follow other related articles on the PHP Chinese website!