题解 | #质数因子#
质数因子
https://www.nowcoder.com/practice/196534628ca6490ebce2e336b47b3607
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); int denominator = 2; while (num > 1) { if (isPrime(num)) { System.out.println(num); return; } while (num % denominator != 0) { denominator++; } num /= denominator; System.out.print(denominator + " "); } } public static boolean isPrime(int n) { if (n < 3) { return false; } int r = n % 6; if (r != 5 && r != 1) { return false; } int s = (int) Math.sqrt(n); for (int i = 5; i <= s; i += 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } }
---------------------------------------------------------------------------------------------------------
2024-06-13 摸鱼中 更新一下 这个题是简单题 之前写的太重了
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); solution(n, 2); System.out.println(PRIME_FACTOR_LIST .stream() .map(String::valueOf) .collect(Collectors.joining(" "))); } private static final List<Integer> PRIME_FACTOR_LIST = new ArrayList<>(); public static void solution(int num, int prime) { // 递归出口 if (num == 1) { return; } if (num % prime == 0) { PRIME_FACTOR_LIST.add(prime); solution(num / prime, prime); } else { if (isPrime(num)) { PRIME_FACTOR_LIST.add(num); return; } solution(num, findNextPrime(prime)); } } public static int findNextPrime(int prime) { int nextPrime = prime + 1; while (true) { if (isPrime(nextPrime)) { return nextPrime; } nextPrime++; } } public static boolean isPrime(int num) { for (int i = 2; i <= (int) Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } }#华为笔试#