此方法将采用Long并返回传递给方法的任何数字的素数LongStream.
factors.java
public LongStream factors(long x){ LongStream factorStream = LongStream.range(1,x+1).filter(n -> x%n == 0); return factorStream; }
利用上述方法首先找到共同因素是可以的.
primeFactors.java
public LongStream primeFactors(long x){ LongStream primeFactorStream = factors(x).filter(n -> factors(n).count() == 0); //doesn't work as factors.java returns a LongStream,which might include non-prime factors,which will not equate to zero. return primeFactorStream; }
如果你想在没有现有的test-for-prime方法的帮助下用单一方法完成它,你可以这样做
原文链接:https://www.f2er.com/javaschema/281645.htmlpublic static LongStream primeFactors(long x) { return LongStream.rangeClosed(2,x) .filter(n -> x % n == 0) .filter(n -> LongStream.rangeClosed(2,n/2).noneMatch(i -> n%i==0)); }
你可以像这样测试方法
IntStream.concat(IntStream.rangeClosed(2,15),IntStream.rangeClosed(90,110)) .forEach(number -> System.out.printf("%3d = %s%n",number,primeFactors(number) .mapToObj(d -> { int p = 0; for(long l = number; l%d == 0; l /= d,p++) l++; return p == 1? String.valueOf(d): d + "^" + p; }) .collect(Collectors.joining(" * "))) ); }
2 = 2 3 = 3 4 = 2^2 5 = 5 6 = 2 * 3 7 = 7 8 = 2^3 9 = 3^2 10 = 2 * 5 11 = 11 12 = 2^2 * 3 13 = 13 14 = 2 * 7 15 = 3 * 5 90 = 2 * 3^2 * 5 91 = 7 * 13 92 = 2^2 * 23 93 = 3 * 31 94 = 2 * 47 95 = 5 * 19 96 = 2^5 * 3 97 = 97 98 = 2 * 7^2 99 = 3^2 * 11 100 = 2^2 * 5^2 101 = 101 102 = 2 * 3 * 17 103 = 103 104 = 2^3 * 13 105 = 3 * 5 * 7 106 = 2 * 53 107 = 107 108 = 2^2 * 3^3 109 = 109 110 = 2 * 5 * 11
不用说,这不是最有效的方法……