javaoj判断质数
时间: 2023-11-01 13:08:04 浏览: 113
Java版求质数
5星 · 资源好评率100%
要使用JavaOJ判断一个数是否为质数,可以参考以下代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
boolean isPrime = true;
if (x <= 1) {
isPrime = false;
}
for (int i = 2; i <= Math.sqrt(x); i++) {
if (x % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("This is a prime.");
} else {
System.out.println("This is not a prime.");
}
}
}
这段代码会从键盘上输入一个正整数x,然后判断x是否为质数。如果x是质数,则输出"This is a prime.",否则输出"This is not a prime."。请注意,这段代码与引用和引用中的代码非常相似,但有一些细微的差别。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [Java语法练习SDUTOJ判断素数(循环结构)](https://blog.csdn.net/Cherishlife_/article/details/85223731)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [ZZULIOJ 1057: 素数判定,Java](https://blog.csdn.net/qq_52792570/article/details/119005501)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文