Home > Java > Javagetting Started > body text

Java small test seeks to complete the number within 1000

王林
Release: 2020-12-08 15:12:47
forward
3142 people have browsed it

Java small test seeks to complete the number within 1000

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);
        }
    }
}
Copy after login

Running result:

完数:6
完数:28
完数:496
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template