`

正则表达式判断是否素数、解线性方程

阅读更多
参考文章:
http://coolshell.cn/articles/2704.html
http://www.programcreek.com/2013/10/top-10-questions-for-java-regular-expression/

java里用正则表达式判断是否素数:
public static boolean prime(int n) {
  return !new String(new char[n]).matches(".?|(..+?)\\1+");
}


还可以解方程:
public static void sovleLinearEquation(int result, int...params) {
        if (result <= 0) {
            throw new IllegalArgumentException("result must be positive");
        }
        if (params == null || params.length == 0) {
            throw new IllegalArgumentException("params must not be empty");
        }
        
        //^(.*)\1{A−1}(.*)\2{B−1}$
        StringBuilder p = new StringBuilder("^");
        for (int i = 0, len = params.length; i < len; i++) {
            int param = params[i];
            if (param <= 0) {
                throw new IllegalArgumentException("param must be positive:" + param);
            }
            p.append("(.*)\\").append(i + 1).append("{").append(param - 1).append("}");
        }
        p.append("$");
        Pattern pattern = Pattern.compile(p.toString());
        Matcher matcher = pattern.matcher(new String(new char[result]));
        if (matcher.find()) {
            StringBuilder exp = new StringBuilder();
            for (int i = 0, len = params.length; i < len; i++) {
                exp.append(" + ").append(params[i]).append(" * ").append(matcher.group(i + 1).length());
            }
            if (exp.length() > 0) {
                exp.append(" = " + result);
                System.out.println(exp.substring(3));
            }
        } else {
            System.out.println("unsovleable");
        }
    }

例如:
sovleLinearEquation(51, 17, 12);
sovleLinearEquation(115, 11, 2, 5);
==》
17 * 3 + 12 * 0 = 51
11 * 10 + 2 * 0 + 5 * 1 = 115
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics