gpt4 book ai didi

java - 如何在循环后的末尾打印另一个术语?在java中

转载 作者:行者123 更新时间:2023-12-01 17:55:33 28 4
gpt4 key购买 nike

import java.util.Scanner;

public class PrimeNumbers {
public static boolean prime(int num) {
boolean flag = true;
for(int i=2;i<=num/2;i++) {
if(num%i==0) {
flag = false;
break;
}

}
return flag;
}
public static void main(String[] args) {
String separator = "";
Scanner scan = new Scanner(System.in);
System.out.println("First num:");
int low = scan.nextInt();
System.out.println("Second num:");
int high = scan.nextInt();
if(low>high||high<=0||low<0||(high-low) == 1) {
System.out.println("Invalid input");
System.exit(0);
}
while(low<high) {
if(prime(low)==true) {
System.out.printf(separator+"%d",low);
separator = ",";
}
low++;
}

}
}
<小时/>

示例:

first num:1
second num:10
Output: 1,2,3,5,7

我的要求是,我需要检查输入的“第二个数字”是否为素数,如果不是素数,则打印下一个素数。

示例:

first num:1
second num:
Output: 1,2,3,5,7,11

最佳答案

int lastNumber = high;
if(!prime(lastNumber))
{
while(!prime(++lastNumber));
// now you have to prime number after the high or that number itself if it
//is the prime
}
// now print all numbers and lastNumber in the last


You did num/2 if the first loop which is good for performance but you can increase
performance even more you can do int sqrt = sqrt(num) , now cast it to int and use it
int the loop
so if num is 100 in your case you will be doing 50 checks , but in sqrt case on 10
checks

关于java - 如何在循环后的末尾打印另一个术语?在java中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60723596/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com