相关疑难解决方法(0)

计算并打印第n个素数

我正在尝试计算素数,我已经完成了.但我想计算并打印第n个素数(用户输入),在计算其余部分(它们不会被打印)时,只打印第n个素数.

这是我到目前为止所写的内容:

import java.util.Scanner;
/**
 * Calculates the nth prime number
 * @author {Zyst}
 */
public class Prime {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int n, 
            i = 2, 
            x = 2;

        System.out.printf("This program calculates the nth Prime number\n");
        System.out.printf("Please enter the nth prime number you want to find: ");
        n = input.nextInt();

        for(i = 2, x = 2; i <= n; i++) {
            for(x = 2; x < i; x++) {
                if(i % …
Run Code Online (Sandbox Code Playgroud)

java primes

38
推荐指数
3
解决办法
9万
查看次数

查找素数的快速算法?

首先 - 我在这个论坛上检查了很多,但我找不到足够快的东西.我尝试创建一个函数,返回指定范围内的素数.例如,我使用Eratosthenes的筛子完成了这个功能(在C#中).我也试过阿特金的筛子但是Eratosthenes的跑得更快(在我的实施中):

public static void SetPrimesSieve(int Range)
    {
        Primes = new List<uint>();
        Primes.Add(2);
        int Half = (Range - 1) >> 1;
        BitArray Nums = new BitArray(Half, false);
        int Sqrt = (int)Math.Sqrt(Range);
        for (int i = 3, j; i <= Sqrt; )
        {
            for (j = ((i * i) >> 1) - 1; j < Half; j += i)
                Nums[j] = true;
            do
                i += 2;
            while (i <= Sqrt && Nums[(i >> 1) - 1]);
        }
        for …
Run Code Online (Sandbox Code Playgroud)

algorithm performance primes sieve-of-eratosthenes

7
推荐指数
1
解决办法
2万
查看次数