怎么写阿
题目内容:编写程序,读入一个整数,然后以升序显示它的所有最小因子,并对这些因子进行求和输出。
输入格式:
整数,number为输入的整数, 数组factor存储因子
输出格式:
System.out.print(number + "'s factor series:");
System.out.print(factor + ", ");
System.out.println("\nthe sum of factors is " + sum);
输入样例:
100
输出样例:
100's factor series:2, 2, 5, 5,
the sum of factors is 14 import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int number = 100;
ArrayList<Integer> factor = new ArrayList<>();
int sum = 0;
for (int i = 2; i <= number; i++) {
while (number % i == 0) {
factor.add(i);
sum += i;
number /= i;
}
}
System.out.print(number + "'s factor series:");
for (int i = 0; i < factor.size(); i++) {
System.out.print(factor.get(i) + ", ");
}
System.out.println("\nthe sum of factors is " + sum);
}
}
isdkz 发表于 2023-11-14 17:51
编写程序,读入一个整数,然后以升序显示它的所有最小因子,并对这些因子进行求和输出。(10分)
题目内容:
编写程序,读入一个整数,然后以升序显示它的所有最小因子,并对这些因子进行求和输出。
输入格式:
整数,number为输入的整数, 数组factor存储因子
输出格式:
System.out.print(number + "'s factor series:");
System.out.print(factor + ", ");
System.out.println("\nthe sum of factors is " + sum);
输入样例:
100
输出样例:
100's factor series:2, 2, 5, 5,
the sum of factors is 14 import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
//number为输入的整数
System.out.println("输入的整数:");
Scanner sc=new Scanner(System.in);
int number=sc.nextInt();
//因子进行求和输出sum
int sum=0;
//使用动态数组ArrayList存储因子
ArrayList<Integer> arrayList=new ArrayList<>();
for (int i = 2; i <=number ; i++) {
while (number%i==0){
arrayList.add(i);
number=number/i;
sum+=i;
}
}
//将动态数组ArrayList转换成int[]
int[] factor = new int;
for(int i = 0;i<arrayList.size();i++){
factor = arrayList.get(i);
}
System.out.print(number + "'s factor series:");
System.out.println(Arrays.toString(factor));
System.out.println("\nthe sum of factors is " + sum);
}
}
页:
[1]