正则表达式判断是否素数、解线性方程_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 正则表达式判断是否素数、解线性方程

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

 2013/10/31 16:13:13  bylijinnan  程序员俱乐部  我要评论(0)
  • 摘要:参考文章:http://coolshell.cn/articles/2704.htmlhttp://www.programcreek.com/2013/10/top-10-questions-for-java-regular-expression/java里用正则表达式判断是否素数:publicstaticbooleanprime(intn){return!newString(newchar[n]).matches(".?|(..+?)\\1+");}还可以解方程
  • 标签:正则表达式 表达式 正则
参考文章:
http://coolshell.cn/articles/2704.html
http://www.programcreek.com/2013/10/top-10-questions-for-java-regular-expression/

java里用正则表达式判断是否素数:
class="java" name="code">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
发表评论
用户名: 匿名