素数判定 ——杭电POJ2012

Problem Description
对于表达式n^2+n+41,当n在(x,y)范围内取整数值时(包括x,y)(-39<=x<y<=50),判定该表达式的值是否都为素数。
 

Input
输入数据有多组,每组占一行,由两个整数x,y组成,当x=0,y=0时,表示输入结束,该行不做处理。
 

Output
对于每个给定范围内的取值,如果表达式的值都为素数,则输出"OK",否则请输出“Sorry”,每组输出占一行。
 

Sample Input
  
  
0 1 0 0
 

Sample Output
  
  
OK
import java.util.Scanner;


public class POJ2012 {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		
		while (cin.hasNext()) {
			int x = cin.nextInt();
			int y = cin.nextInt();
			
			if (x == 0 && y == 0) 
				break;
			
			int num = 0;
			
			for (int i = x; i <= y; i ++) {
				int n = i * i + i + 41;
				
				if (sushu(n))
					num ++;
			}
			
			if (num == (y - x + 1))
				System.out.println("OK");
			else
				System.out.println("Sorry");
		}
	}
	
	public static boolean sushu(int n) {
		if (n < 2) return false;
		if (n == 2) return true;
		for (int i = 3; i * i < n; i += 2) {
			if (n % i == 0) 
				return false;
		}
		return true;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值