|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目内容:
编写程序,读入一个整数,然后以升序显示它的所有最小因子,并对这些因子进行求和输出。
输入格式:
整数,number为输入的整数, 数组factor存储因子
输出格式:
System.out.print(number + "'s factor series:");
System.out.print(factor[i] + ", ");
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[arrayList.size()];
for(int i = 0;i<arrayList.size();i++){
factor[i] = 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);
}
}
|
|