本文主要是介绍素数判定和分解质素数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.素数判定
public static boolean isPrime(int n) {if (n <= 1) return false;if (n == 2) return true;if (n % 2 == 0) return false;int limit = (int)Math.sqrt(n) + 1;for (int i = 3; i <= limit; i += 2) {if (n % i == 0) {return false;}}return true;}
2.分解质素数
public static List<Integer> getPrimeFactor(int n) {if (n <= 1) {return new ArrayList<Integer>();}List<Integer> factors = new ArrayList<Integer>();int number = n;int factor = 2;while (factor <= number) {if (number % factor == 0) {factors.add(factor);number /= factor; } else {factor++;// next prime factor?}}return factors;}
这篇关于素数判定和分解质素数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!