本帖最后由 棉/mg花/x糖 于 2013-5-27 23:25 编辑
程序改进,源码如下:
- package com.yb.FindPerfectNumber;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class FindPerfectNumber {
- static void findPerfectNum(int n) {
- int i,j,s,k = 0;
- for(i = 1; i <= n; i++) {
- s = 0;
- for(j = 1; j < i; j++) {
- if(i%j == 0) s += j;
- }
- if(s == i) {
- System.out.print(i+" = ");
- for(j = 1; j < i/2; j++)
- System.out.print(i%j==0 ? j+"+":"");
- System.out.println(i/2); //输出最后一个因子
- k++;
- }
- }
- System.out.println("\n"+n+"之内的完全数共有 "+k+" 个!");
- }
- public static void main(String []args) throws IOException {
- System.out.println("请从键盘输入一个整数n(n<2147000000):");
- BufferedReader keyin = new BufferedReader(new InputStreamReader(System.in));
- String ch = keyin.readLine();
- int n = Integer.parseInt(ch);
- System.out.println("\n要寻找 "+n+"以内的完全数:\n");
- findPerfectNum(n);
- }
- }
复制代码 运行效果截图:
|