【问题标题】:how can i determine all prime numbers smaller than a given input value? [duplicate]如何确定小于给定输入值的所有素数? [复制]
【发布时间】:2019-03-26 09:42:24
【问题描述】:

任何人都可以帮助我使用带有 java8 的扫描仪确定所有小于给定输入值的素数。

输入:N个整数> 0

输出:带有素数的表格。

示例:对于 N = 10,输出为:2 3 5 7

这是我目前的工作:

class Main {
public static void main(String[] args) {
    int N;
    int[] result = null;

    try (Scanner scanner = new Scanner(new File(args[0]))) {
        N = Integer.parseInt(scanner.nextLine());
         
          for (int i = 0; i < (N/2)+1; i++) {
            if (N%i==0)
                result[i]=i;
        for (int j = 0; j < result.length; j++) {
            System.out.print(result[j]);
            if (j < result.length - 1) {
                System.out.print(" ");
            }
        }
        }
        System.out.println();
    }
    catch (FileNotFoundException ex) {
        throw new RuntimeException(ex);
    }
 }
}

【问题讨论】:

  • 你可以使用prime sieve
  • en.wikipedia.org/wiki/Primality_test,如果你真的想做一个算法,在这里你可以选择你喜欢的方法。老实说,它认为存储一个所有初选数低于 10000 的数组会更容易,并在你的函数中返回该数组的一部分。
  • 为什么从零开始i,为什么到N/2
  • @khelwood 我不能用 java 写它!
  • @N8888 不重复

标签: java algorithm math


【解决方案1】:

您的代码问题是int i = 00 开头,下一行if (N%i==0) 所以10/0 不可能抛出类似java.lang.ArithmeticException: / by zero 的错误是不可能的

并且您循环通过result.length,您需要循环通过i 您的父循环并将条件放入if (N%i==0) 并且您需要进行许多更改,看到我的下面的答案和调试,您会得到意外的输出并遵循。

蛮力

public static void main(String[] args) {
        int N = 50;
        List<Integer> result = new ArrayList<>();
        for (int i = 1; i < N; i++) {
            boolean isPrime = true;
            for (int j = 2; j < i - 1; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                result.add(i);
            }
        }
        result.forEach(System.out::println);

    }

使用Math.sqrtreason优化一个

public static void main(String[] args) {
        int N = 101;
        List<Integer> result = new ArrayList<>();
        for (int i = 1; i <= N; i++) {
            boolean isPrime = true;
            for (int j = 2; j < Math.sqrt(i - 1); j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                result.add(i);
            }
        }
        result.forEach(System.out::println);
}

使用BigInteger.isProbablePrimesee

public static void main(String[] args) {
        int N = 101;
        List<Integer> result = new ArrayList<>();

        for (long i = 1; i <= N; i++) {
            BigInteger integer = BigInteger.valueOf(i);
            if (integer.isProbablePrime(1)) {
                result.add((int) i);
            }
        }
        result.forEach(System.out::println);

    }

更新 1:- 你想要的东西

try (Scanner scanner = new Scanner(new File(args[0]))) {
            int N = Integer.parseInt(scanner.nextLine());
            int[] result = new int[N];
            int resultIncreamenter = 0;
            // here for loop logic can be replaced with above 3 logic
            for (int i = 1; i <= N; i++) {
                boolean isPrime = true;
                for (int j = 2; j < Math.sqrt(i - 1); j++) {
                    if (i % j == 0) {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime) {
                    result[resultIncreamenter++] = i;
                }
            }
            for (int j = 0; j < result.length; j++) {
                System.out.print(result[j]);
                if (j < result.length - 1) {
                    System.out.print(" ");
                }
            }
            System.out.println();
        } catch (FileNotFoundException ex) {
            throw new RuntimeException(ex);
        }

【讨论】:

  • 谢谢 :) 但我的扫描仪输入总是有问题..!如果您要查找第一个代码,我必须在此处更改 /* for (int i = 0; i
  • @Mourad9 更新了你想要的答案
  • 谢谢你能给我你的电子邮件请告诉我有什么要问的
【解决方案2】:

您失去了概览,尽管您可以使用所有功能。

public static boolean isPrime(int n) {
    for (int i = 0; i < (n/2)+1; i++) {
        if (n%i == 0) {
            return false;
        }
    }
    return true;
}

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(new File(args[0]))) {
        int N = Integer.parseInt(scanner.nextLine());

        boolean printed = false;
        for (int j = 2; j < N; j++) {
            if (isPrime(j)) {
                if (printed) {
                    System.out.print(" ");
                }
                System.out.print(j);
                printed = true;
            }
        }
        System.out.println();
    } catch (FileNotFoundException ex) {
        throw new RuntimeException(ex);
    }
}

只需使用像isPrime 这样的抽象。

现在进行改进(您的results 数组):在测试中使用已经找到的素数而不是所有数字:

public static boolean isPrime(int n, int[] priorPrimes, int primesCount) {
    for (int p : priorPrimes) {
        if (n%p == 0) {
            return false;
        }
    }
    return true;
}


public static void main(String[] args) {
    try (Scanner scanner = new Scanner(new File(args[0]))) {
        int N = Integer.parseInt(scanner.nextLine());

        int[] primes = new int[N];
        int primesCount = 0;
        boolean printed = false;
        for (int j = 2; j < N; j++) {
            if (isPrime(j)) {
                primes[primesCount] = j;
                ++primesCount;
                if (printed) {
                    System.out.print(" ");
                }
                System.out.print(j);
                printed = true;
            }
        }
        System.out.println();
    } catch (FileNotFoundException ex) {
        throw new RuntimeException(ex);
    }
}

【讨论】:

    【解决方案3】:

    使用来自here的埃拉托色尼筛法的算法:

    private static int findNumberOfPrimes(int length) {
        int numberOfPrimes = 1;
        if (length == 2) {
            return 1;
        }
    
        int[] arr = new int[length];
        //creating an array of numbers less than 'length'
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }
        //starting with first prime number 2, all the numbers divisible by 2(and upcoming) is replaced with -1
        for (int i = 2; i < arr.length && arr[i] != -1; i++) {
    
            for (int j = i; j < arr.length; j++) {
                if (arr[j] % arr[i] == 0) {
                    arr[j] = -1;
                    numberOfPrimes += 1;
                }
            }
        }
        return numberOfPrimes;
    }
    

    更新

    这就是你列出它们的方式:

    package primelessthanN;
    
    public class Main {
    
        public static void main(String[] args) {
            int j;
            int n;
            n = 10;
    
            for (j = 2; j <=n; j++) {
                if (isPrime(j))
                    System.out.println(j);
            }
        }
    
        private static boolean isPrime(int m) {
            for (int i = 2; i <= sqrt(m); i++) {
                if (m % i == 0)
                    return false;
            }
            return true;
        }
    }
    

    【讨论】:

    • 这里你计算素数而不是素数本身!
    • 你没有说你想要素数本身。但我更新了它以包括它。您可以使 n 等于任何值。这是 10 的值
    • 我的扫描仪输入总是有问题..!如果您要查找第一个代码,我必须在此处更改 /* for (int i = 0; i
    猜你喜欢
    • 2021-01-31
    • 2014-07-21
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 2020-01-03
    • 2021-10-24
    相关资源
    最近更新 更多