This article describes the implementation of Java's complete output algorithm for a specific range. Share it for your reference, as follows:
Question content:
The factor of a positive integer is all positive integers that can be divided into it. If a number is exactly equal to the sum of factors other than itself, this number is called the complete number.
For example, 6=1+2+3 (the factor of 6 is 1, 2, 3).
Now, you need to write a program to read in two positive integers n and m (1<=n<m<1000), and output all the completed numbers in the range [n,m].
Tip: You can write a function to determine whether a certain number is a complete number.
Input format:
Two positive integers separated by spaces.
Output format:
All the finished numbers are separated by spaces, and there are no spaces after the last number. If not, a blank line is output.
Enter a sample:
1 10
Output sample:
6
Code example:
import java.util.Scanner;public class Main { //Judge whether it is a complete number public static boolean isFinishedNum(int n) { //Exclude interference 1, 2 if((n==1)||(n==2)) return false; boolean isFinishedNum = false; int sum=1; for(int i =2;i<n;i++) { if(n%i==0) sum+=i; } //If equal is complete number if(sum==n) isFinishedNum = true; return isFinishedNum; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Wulin.com- Completed output test within a specific range: "); Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); String out = " "; for(int i =n;i<=m;i++) { if(isFinishedNum(i)) out = out+i+" "; } //Remove the spaces on both sides of out out=out.trim(); System.out.println(out); in.close(); }}Running results:
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.