数素数

题目描述

令Pi表示第i个素数。现任给两个正整数M <= N <= 10000,请输出PM到PN的所有素数。

输入描述:

输入在一行中给出M和N,其间以空格分隔。


输出描述:

输出从PM到PN的所有素数,每10个数字占1行,其间以空格分隔,但行末不得有多余空格。

输入例子:

5 27

输出例子:

11 13 17 19 23 29 31 37 41 43

47 53 59 61 67 71 73 79 83 89

97 101 103

题目摘自牛客网点击打开链接

下面是我写的代码,并测试通过。

import java.util.Scanner;

public class T5 {

	public static void main(String[] args) {
		int begin;
		int end;
		Scanner sc = new Scanner(System.in);
		begin = sc.nextInt();
		end = sc.nextInt();
		int counterPrime=0;
		int counterN=0;
		int n=2;//从2开始的数字
		StringBuffer sb = new StringBuffer();
		
	  
		while(true){
			if(isPrime(n)){
				counterPrime++;
				if(counterPrime>=begin&&counterPrime<=end){
					counterN++;
					//sb.append(n+" ");
					if(counterN%10==0){
						sb.append(n+"\n");
					}else if(counterPrime==end){
						sb.append(n);
						break;
					}else{
						sb.append(n+" ");
					}
				}
			}
				n++;
			if(counterPrime==10000){
				break;
			}
		}
		System.out.println(sb.toString());
	}
	

	static boolean isPrime(int d){
		if(d==1)
			return false;
		 double result =Math.sqrt(d);
		 int j= (int)result;
		for(int i=2;i<=j;i++)
			if(d%i==0){
				return false;
			}
			return true;
	}
}
结果如图:


这道题的核心就是怎么判断素数,代码中isPrime方法为判断素数的方法,然后再注意题目的格式要求基本就能做出来,总体来说难度不大。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值