【问题标题】:While loop that will cycle through entries in array java将循环遍历数组java中的条目的while循环
【发布时间】:2018-12-29 08:29:24
【问题描述】:

好的,所以我正在尝试设置一个可以找到素数的程序。我已经设置了一个名为 primes 的数组,其素数最多为 199。如何创建一个几乎可以说 while (x%primes[any number in primes]

import static java.lang.System.out;
public class Problem3 {

public static void main(String[] args) {
    /// What is the largest prime factor of the number 600851475143 ?
        long x;
        x = 600851475143L;
        int[] primes = {
            2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
        };
        out.println(x);
        //while (x % primes[*This is where I need clarification*] <= 0) {
            int i = 0;

                for (i = 0; i < primes.length; i++) {
                    //out.println("Term " + i + " is " + primes[i]);
                        if (x%primes[i] <=0) {
                            x = x/primes[i];
                        }

                }   
        //}

        out.println(x);

}

}

This answer worked for me!

【问题讨论】:

  • while循环应该做什么?不清楚
  • @Sand 我很抱歉。我需要 while 循环处于活动状态,而主数字仍可被数组中的数字整除。不过我的设置很时髦,另一个用户帮了我!
  • 很高兴知道它已经解决了
  • @Morgan 请使用解决方案发布您自己问题的答案。

标签: java arrays while-loop


【解决方案1】:

您的素数表太小(只有71600851475143L 的因子)。最简单的解决方法是消除该表并从 3 迭代到您的数字的平方根以 2 递增。喜欢,

long x = 600851475143L;
for (int i = 3; i <= Math.sqrt(x); i += 2) {
    if (x % i == 0) {
        System.out.println(i);
        x /= i;
    }
}
System.out.println(x);

我明白了

71
839
1471
6857

71*839*1471*6857
600851475143

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多