[英]Print arithmetic progression using prime number java
there.那里。 I just make a arithmetic progression using prime number, i have shown the prime number, but when i want to print the arithmetic progression, it print something else.我只是使用素数做一个算术级数,我已经显示了素数,但是当我想打印算术级数时,它会打印其他东西。
Here's what i want to display:这是我要显示的内容:
1 3 6 11 18
This is my current code:这是我当前的代码:
for(int i=2;i<=20;i++){
boolean isPrime = true;
for(int j=2; j < 1; j++){
if(i%j==0){
isPrime = false;
break;
}
}
if(isPrime){
for (int k=1; k<=10; k++){
System.out.print(k + " ");
k+=i;
}
}
The display what's shown:显示显示的内容:
1 4 7 10 1 5 9 1 6 1 7 1 8 1 9 1 10 1 1 1 1 1 1 1 1 1 1 1 1
Can someone help me with this?有人可以帮我弄这个吗? Thank you before之前谢谢
You need to make some changes in the algo, especially in the inner loop您需要在算法中进行一些更改,尤其是在内部循环中
int sum = 0;
for (int i = 1; i <= 20; i++) {
boolean isPrime = true;
for (int j = i-1; j > 1; j--) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
sum = sum + i;
System.out.println(sum);
}
}
for (int j = i-1; j > 1; j--)
We are doing this because we want to see if the number is prime. for (int j = i-1; j > 1; j--)
我们这样做是因为我们想看看这个数是否是素数。 You can improve this logic by starting setting j to sqrt(I).您可以通过将 j 设置为 sqrt(I) 来改进此逻辑。
I think the best way to figure out the problem is to create a method that will return the next prime number, and to store the current number (the one that will get displayed ) in a variable so that each time it is displayed it gets upddated by incrementing it by the next prime number as shown in the code below:我认为解决问题的最佳方法是创建一个返回下一个素数的方法,并将当前数字(将显示的那个)存储在一个变量中,以便每次显示它都会更新通过将其增加下一个素数,如下面的代码所示:
public static void main(String[] args){
int currentNumber = 1 ;
int currentPrime = 2 ;
int limit = 20 ;
while(currentNumber <= limit) {
System.out.print(" " + currentNumber + " ");
currentNumber += currentPrime;
currentPrime = nextPrimeNumber(currentPrime);
}
}
private static int nextPrimeNumber(int currentPrime) {
while(true) {
if(isPrimeNumber(++currentPrime)) return currentPrime;
}
}
private static boolean isPrimeNumber(int number) {
for(int i = 2 ; i <= (int) Math.sqrt(number) ; i++) {
if(number % i == 0) return false;
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.