【问题标题】:Smallest Factor in ArrayListArrayList 中的最小因子
【发布时间】:2019-07-20 02:14:23
【问题描述】:

我正在开发一个程序,该程序接受用户输入,然后打印因素列表。

我对如何打印列表中最小的因素感到困惑。

有什么建议吗?

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print("Enter integer: ");
    long num = input.nextLong();

    ArrayList<Long> list1 = new ArrayList<>(), list2 = new ArrayList<>();



    for(long i = 1; i <= Math.sqrt(num); i++) {
        if(num % i == 0) {
            list1.add(i);
            if(i != num/i) {
                list2.add(num/i);
            }
        }
    }

    int n1 = list1.size() - 1;
    int n2 = list2.size() - 1;

    for(int i = 0; i <= n1; i++) {
        System.out.println(list1.get(i));
    }

    for(int i = n2; i >= 0; i--) {
        System.out.println(list2.get(i));

    }

【问题讨论】:

  • “最小因素”是什么意思?最小因子始终为 1,即list1.get(0)

标签: java arraylist


【解决方案1】:

根据您当前的代码,您可能希望实现某种搜索功能来运行您的数组列表。对于初学者,您可以使用基本的线性搜索(一次检查每个项目)。

您需要一个地方来存储当前的最小因子 (int currSmallest)。然后,您将创建一个 for 循环来遍历每个项目(正如您打印所有项目所做的那样),而是检查该项目是否小于您的 currSmallest 如果是,则将 currSmallest 替换为新因子。

如果您想要代码,我可以为您编写代码,但我认为您了解所有必要的组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多