打印素数从2到1000

编程入门 行业动态 更新时间:2024-10-27 14:32:01
本文介绍了打印素数从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

本文发布于:2023-10-20 22:15:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1512297.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:素数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!