我在朋友的帮助下做了这个,以便找到完美的数字(除数之和=原始数字的数字)总和,直到用户输入的数字。有人可以帮我转换它,以便它打印一行上的每个数字,即使它不是一个完美的数字,并列出所有的除数,然后如果它是完美的,它会在除数后打印出完美的数字?所以喜欢" 6:1,2,3,6,完美数字"不使用数组?
import java.util.*;
public class PerfNumbers {
public static void main(String[] args){
System.out.println("Enter A Number:");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int sumOfDivisors = 0;
for (int number = 1; number <= input; number++){
for (int divisor = 1; divisor < number; divisor++)
{
if (number % divisor == 0)
sumOfDivisors += divisor;
}
if (sumOfDivisors == number)
{
System.out.println(number);
}
sumOfDivisors = 0;
}
sc.close();
}
}
答案 0 :(得分:1)
import java.util.*;
/**
*
* @author Tyler Weaver
*/
public class Test {
public static void main(String[] args) {
System.out.print("Enter A Number: ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int sumOfDivisors = 0;
Collection<Integer> col = new ArrayList<>();
for (int number = 1; number <= input; number++) {
for (int divisor = 1; divisor < number; divisor++) {
if (number % divisor == 0) {
sumOfDivisors += divisor;
col.add(divisor);
}
}
if (sumOfDivisors == number) {
System.out.printf("Perfect Number: %,d%n[", number);
for (Integer i : col) {
System.out.printf("%,d, ", i);
}
System.out.printf("\b\b]%n");
}
sumOfDivisors = 0;
col.clear();
}
sc.close();
}
}
刚刚添加了一个集合来跟踪除数,然后添加了一个printf()语句来正确格式化。
编辑:不使用集合的代码。
import java.util.*;
/**
*
* @author Tyler Weaver
*/
public class Test {
public static void main(String[] args) {
System.out.print("Enter A Number: ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int sumOfDivisors = 0;
for (int number = 2; number <= input; number++) {
System.out.printf("Number: %,d%n[", number);
for (int divisor = 1; divisor < number; divisor++) {
if (number % divisor == 0) {
sumOfDivisors += divisor;
System.out.printf("%,d, ", divisor);
}
}
System.out.printf("\b\b]%n");
if (sumOfDivisors == number) {
System.out.printf("Therefore %,d is a perfect number.%n%n",
number);
} else {
System.out.printf("%n");
}
sumOfDivisors = 0;
}
sc.close();
}
}
答案 1 :(得分:0)
public static void main(String[] args)
{
int i=6;
int n=i;
int r=0;
while(i>0){
i--;
if(i>0 && n%i==0){
if (i!=0)
r=r+i;
}
}
System.out.println(r);
if (r==n)
System.out.println("its True");
else
System.out.println("its False");
}