这是一段看似非常特殊的C++代码.出于某种奇怪的原因,奇迹般地对数据进行排序使得代码几乎快了六倍.
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster.
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c) …Run Code Online (Sandbox Code Playgroud) 我正在尝试计算素数,我已经完成了.但我想计算并打印第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) 我已经研究了Eratosthenes的Sieve的工作,使用迭代生成到达给定数字的素数并且去掉所有复合数.并且算法只需要迭代到sqrt(n),其中n是我们需要找到所有素数的上限. 我们知道,与复合数的数量相比,最多n = 10 ^ 9的素数的数量非常少.因此,我们使用所有空间来通过标记它们的复合来告诉这些数字不是首要的.我的问题是我们可以修改算法只是存储素数,因为我们处理的范围非常大(因为素数的数量非常少)?我们可以直接存储素数吗?
algorithm optimization primes sieve-of-eratosthenes space-complexity