【发布时间】:2019-04-21 12:34:53
【问题描述】:
我和我的朋友正在做一个大学家庭作业,以制作一个没有任何乘法、除法和for 循环的 Eratosthenes-sieve。
问题是我在教授告诉我们不要使用这些东西之前写了它,现在我不知道该怎么做。
将for 循环更改为while 循环没什么大不了的,但我不知道如何摆脱代码末尾的最后一个乘法。
我的朋友做了一些我不明白的更改(我会评论他所做的更改),如果有人可以向我解释解释,我将非常感激。总结:
我们需要去掉
for循环并用while循环替换它们去掉代码末尾的乘法,这是我的主要问题。
帮助了解 cmets 中记录的更改。
我们的代码:
import java.util.Scanner;
public class primesieb {
public static void main(String[] args) {
//so we declare values and used the scanner to make an input.
int input = 0;
Scanner in = new Scanner(System.in);
System.out.println("give an int bigger that 1: ");
input = in.nextInt();
while (input <= 1)
{
//in case the number is smaller than 1.
System.out.println("the Int must be bigger than 1!.");
System.out.println("write an Int bigger than 1: ");
input = in.nextInt();
}
in.close();
//now first i wrote it without "+1" but my friend changed it to +1
boolean[] x = new boolean[input + 1];
//here I just wanted to add this to set that the position 0 in the string is not a prime number but after thinking I don't see its necessary
x[0]=false;
//he did write this commented for loop to assume that all of them are false but for me, it doesn't make sense, pls explain if it's necessary.
//for (int i = 2; i < x.length; i++) {
// x[i] = false;}
for (int i = 2; i < x.length; i++) {
while (x[i])
{
i++;
}
// here how can we get rid of the multiplication.
//the next for loop and if my friend did and a better explain would be nice helping me to represent my code better.
for (int j = i; j*i < input; j++)
{
x[i * j] = true;
}
if (! x[i] && i < input)
{
System.out.println("the number" + i + "is prime. ");
}
}
}
}
我们在 Eclipse 上测试了这段代码,它可以工作,但我们需要避免使用乘法。
【问题讨论】:
-
提示:X、2X、3X等序列与X、X+X、(X+X)+X...
-
@RealSkeptic。你说的是这部分吧??? for (int j = i; j*i 我完全同意这在数学上是 1000% 正确的,但我不知道如何在代码中引入它。对不起,但我的大脑仍然没有得到整个编码逻辑。我是初学者,恐怕我不得不请你向我解释如何用java编写它。感谢您尝试帮助我,我很感激。
-
我现在尝试使用 (int)Math.sqrt(i),但在 primesiebselber.main(primesiebselber.java: 31) 我不知道这是什么。我确实尝试过 (int j = i, z= (int)Math.pow (i,j); z
标签: java primes sieve-of-eratosthenes