没做出来啊,原来有这么多方法啊。
首先,我连质数是什么都不知道!
质数:只能被本身和1整除的数
帖子里回复了不少方法:
class Zhishu
{
public static void main(String[] args)
{
int count=0;
for(int i=1;i<=100;i++)
{
count=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==2||count==1)
{
System.out.print(i+" ");
}
}
}
}
package com.ms.test;
public class GetSushu {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int x=100;x<=999;x++){
boolean flag=true;
for(int y=2;y<x;y++){
if(x%y==0){
flag=false;
break;
}
}
if(flag){
System.out.println(x);
}
}
}
}
判断某一个三位数是否是质数
import java.util.Scanner;
public class PrimeNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个三位数");
int num = sc.nextInt();
if(num<100 || num>999)
throw new RuntimeException("输入数据不合要求");
getPrime(num);
}
public static void getPrime(int num){
for(int x=2;x<num;x++){
if(num%x!=0){
if(x==num-1){
System.out.println(num+"是质数");
}
continue;
}
else{
System.out.println(num+"不是质数");
break;
}
}
}
}
列出所有介于100到你输入的三位数中的质数(不包含100)
import java.util.Scanner;
public class TotalPrimeNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个三位数");
int num = sc.nextInt();
if(num<100 || num>999)
throw new RuntimeException("输入数据不合要求");
getPrime(num);
}
public static void getPrime(int num){
int count = 0;//计数器记录质数个数
W:for (int x = 101; x <= num; x++) {
Q:for (int y = 2; y < x; y++) {
if(x%y!=0){
if(y==x-1){
System.out.print(x+"\t");
count++;
continue W;
}
continue Q;
}
else{
continue W;
}
}
}
System.out.println();
System.out.println("101到"+num+"共有质数个数为:"+count);
}
}
经过上机,就记住第二种(使用flag标记判断)方法吧。
另外,上机时也发现了自己对 if — break 判断的不熟练,
for (int y = 2; y < x; y++) {
if (x % y == 0) {
flag = false;
break;
}
}
例如,上面的循环,如果符合条件,
break之后就中断了for循环了。
注意:break是中断当前最近的一个for循环。
转载于:https://blog.51cto.com/sesedese/1585738