使用正则表达式判断一个数是否为素数

17 篇文章 0 订阅

正则表达式能够用于判断一个数是否为素数,这个以前完全没有想过。

本文将给出一个使用正则判断素数的方法,该正则表达式来源于网页http://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex
正则表达式为.{0,1}|(.{2,})\\1+

正则含义

.{0,1}                        ### The first part of the alternation matches String of length 0 or 1 (NOT prime by definition)
|                             ### Or 
(.{2,})\\1+                   ### The second part of the alternation, a variation of the regex explained above, matches String of length n that is "a multiple" of a 
                                  String of length k >= 2 (i.e. n is a composite, NOT a prime). 

代码如下:

public class CheckPrimeUsingRegex {

	public static boolean isPrime(int n) {
		return !new String(new char[n]).matches(".{0,1}|(.{2,})\\1+");
	}
}

 
测试输出100以内的所有素数

public class CheckPrimeUsingRegexTest {
	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			if (CheckPrimeUsingRegex.isPrime(i)) {
				System.out.println(i);
			}
		}
	}
}

 

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

这种判断素数的方法适合小一点的数,并不适合判断比较大的数值,数字很大时容易产生OutOfMemoryError。

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Unknown Source)
	at java.lang.String.<init>(Unknown Source)
	at CheckPrimeUsingRegex.isPrime(CheckPrimeUsingRegex.java:13)
	at CheckPrimeUsingRegexTest.main(CheckPrimeUsingRegexTest.java:4)

 

原文地址 http://thecodesample.com/?p=1006

更多的例子请访问 http://thecodesample.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值