java - 如何在Java中将一个数字除以其最低因子直到数字变为1
问题描述
我想要一个程序,如果用户输入一个数字,例如 20,那么它应该将该数字除以 2(第一个非一个因素)并得到 10。然后它应该检查这个数字是否为一个。如果是然后除以 2 得到 5,最后除以 5 得到 1。那么程序应该停止。但我无法理解除第一个数字后要执行什么步骤。然后最后输出应该是 20+10+5+1,即 36。这是我的代码:
import java.io.*;
import java.util.*;
public class PrimeFactor {
public static void main(String args[] ) throws Exception {
//Write code here
Scanner s = new Scanner(System.in);
String val = s.nextLine();
int number = Integer.parseInt(val);
int total = 0;
String num = s.nextLine();
String[] strings = num.split(" ");
for(int i=0; i<number; i++){
int current = Integer.parseInt(strings[i]);
if(current == 1){
total ++;
} else if(current > 1){
total += current + 1;
ArrayList<Integer> numbers = new ArrayList<>();
for(int j = 2; j<=current; j++){
if(current % j == 0){
numbers.add(j);
}
}
total += current / numbers.get(0);
} else if (current < 0){
ArrayList<Integer> numbers = new ArrayList<>();
for (int j = current; j <= current * -1; j++){
numbers.add(j);
}
total += current / numbers.get(0);
}
}
System.out.println(total);
}
}
import java.io.*;
import java.util.*;
public class PrimeFactor {
public static void main(String args[] ) throws Exception {
//Write code here
Scanner s = new Scanner(System.in);
String val = s.nextLine();
int number = Integer.parseInt(val);
int total = 0;
String num = s.nextLine();
String[] strings = num.split(" ");
for(int i=0; i<number; i++){
int current = Integer.parseInt(strings[i]);
if(current == 1){
total ++;
} else if(current > 1){
total += current + 1;
ArrayList<Integer> numbers = new ArrayList<>();
for(int j = 2; j<=current; j++){
if(current % j == 0){
numbers.add(j);
}
}
total += current / numbers.get(0);
} else if (current < 0){
ArrayList<Integer> numbers = new ArrayList<>();
for (int j = current; j <= current * -1; j++){
numbers.add(j);
}
total += current / numbers.get(0);
}
}
System.out.println(total);
}
}
解决方案
代码不需要那么复杂。问题中提供的代码中缺少几件事。首先,total
不是每个数字都设置为 0。其次,您只为一个因素划分一次。
下面是计算一个数字的输出的示例。您可以将其用作代码中的函数。
import java.util.*;
class PrimeFactor {
public static void main(String args[] ) throws Exception {
Scanner s = new Scanner(System.in);
int num = s.nextInt();
int total = num;
int factor = 2;
while (factor <= num) {
if (num % factor == 0) {
total += num/factor;
num = num / factor;
} else {
factor++;
}
}
System.out.println(total);
}
}
推荐阅读
- rust - 取消引用指向已删除值的指针并且内存仍然存在
- c++ - 为向量的每个元素添加价值的最快方法
- active-directory - 如何将我的 Nextcloud 与我的 Samba 服务器连接?
- java - List.contains() 为违反 hashCode 合约的对象返回 true
- function - 我该如何解决: One :: Num a => a -> Bool -> a in Haskell?
- javascript - FabricJs:将对象大小固定在组调整大小上
- android - 在linux中构建cordova应用程序时出错
- flutter - Flutter 如何使用 httpServer 接收数据
- java - 即使使用调度程序,记分板也不会更新
- python - 在 pandas 中使用 openpyxl 编写时损坏的工作簿