打印素数从2到1000 [英] Printing out Prime Numbers from 2 to 1000

查看:142
本文介绍了打印素数从2到1000的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个代码,将2到1000之间的所有素数写入一个名为primes.txt的文件中.由于某种原因,我无法找出解决此问题的正确方法.

I am writing a code that write all the prime numbers from 2 to 1000 in a file, named primes.txt. For some reason I am not able to figure out the correct way to do this problem.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Problem6 {

    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter prw = new PrintWriter("primes.txt");
        for (int i = 2; i <= 1000; i++){
            if (checkIfPrime(i) == true){
                System.out.println(i);
                prw.println(i);
            }
        }
    }

    public static boolean checkIfPrime (int num){
        boolean isPrime = true;  
        for (int i = 2; i <= 1000; i++){
            if ( num % i == 0 ){
                isPrime = false;
            }
        }

        return isPrime;
    }
}

我只是不知道该怎么办...请帮助谢谢!

I just dont know what to do... Please help Thanks!

推荐答案

当您将第一个数字2传递给checkIfPrime时会发生什么?它将2的余数除以2(即0),错误地声称2不是素数.

What happens when you pass in your first number, 2, to checkIfPrime? It will take remainder of 2 divided by 2, which is 0, falsely claiming that 2 is not prime.

在实际进入num之前,您需要停止测试余数.在i进入num之前,停止您的i循环. (实际上,您可以在i到达num的平方根后停止.)

You need to stop testing remainders before you actually get to num. Stop your i for loop before i gets to num. (In fact, you can stop after i has reached the square root of num).

for (int i = 2; i < num; i++){

甚至

for (int i = 2; i <= Math.sqrt(num); i++){

如果您喜欢冒险,可以尝试实施筛网筛网,该标志所有组合数字,直到任意限制(在此问题中为1000).然后,您只需打印出其余的数字-质数即可.

If you're feeling adventurous, you may try implementing the Sieve of Eratosthenes, which marks all composite numbers up to an arbitrary limit (in this question, 1000). Then you just print out the rest of the numbers -- the primes.

这篇关于打印素数从2到1000的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆