当前位置:首页 > 开发 > 编程语言 > 正则表达式 > 正文

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

发表于: 2013-10-31   作者:bylijinnan   来源:转载   浏览:
摘要: 参考文章: 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) { re
参考文章:
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

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号