Prime number 质数相关. 3927
什么是质数?在一个大于1的自然数中,除了1和此整数自身外,没法被其他自然数整除的数,比如:2,3,5,7,11...
什么是合数?比1大但不是素数的数称为合数。1和0既非素数也非合数。合数是由若干个质数相乘而得到的, 比如:4,6,8,9,10...
如何判定一个数是否位质数?
时间复杂度:O(sqrt(N))
public class Main { public static void main(String[] args) { System.out.println(isPrime(3)); } //一个数N的最大质数因子<=sqrt(N),因此我们只需要判定到 i*i <= n 即可 private static boolean isPrime(int n) { for(int i = 2; i * i <= n; i++) { if(n % i == 0) return false; } return true; } }
给出一个数字n,列出小于n的所有质数
时间复杂度:O(N)
private void countPrime(int num, List<Integer> set) { //初始化2~num+1认为都不是质数 boolean[] isNotPrime = new boolean[num + 1]; //逐个进行判定是否位质数 for(int i = 2; i <= num; i++) { //如果被标记为不是质数,那么直接continue if(isNotPrime[i]) continue; //否则就是质数 set.add(i); //如果是质数,那么标记所有它的倍数数字为合数 for(long j = (long)i * i; j <= num; j = j + i) { isNotPrime[(int)j] = true; } } }
更快的方法:O(sqrt(N))
def getPrime(max_num): plist = [] d = 2 x = max_num while d * d <= x: if x % d == 0: plist.append(d) while x % d == 0: x //= d d += 1 if x > 1: plist.append(x) return plist
3927. Minimize Array Sum Using Divisible Replacements
You are given an integer array
nums.You can perform the following operation any number of times:
- Choose two indices
aandbsuch thatnums[a] % nums[b] == 0. - Replace
nums[a]withnums[b].
Return the minimum possible sum of the array after performing any number of operations.
Example 1:
Input: nums = [3,6,2]
Output: 7
Explanation:
- Choose
a = 1,b = 2, wherenums[a] = 6andnums[b] = 2. Since6 % 2 == 0, replacenums[1]withnums[2]. - The array becomes
[3, 2, 2]. - No further operation reduces the sum. Thus, the final sum is
3 + 2 + 2 = 7.
Example 2:
Input: nums = [4,2,8,3]
Output: 9
Explanation:
- Choose
a = 0,b = 1, wherenums[a] = 4andnums[b] = 2. Since4 % 2 == 0, replacenums[0]withnums[1]. - Choose
a = 2,b = 1, wherenums[a] = 8andnums[b] = 2. Since8 % 2 == 0, replacenums[2]withnums[1]. - The array becomes
[2, 2, 2, 3]. - No further operation reduces the sum. Thus, the final sum is
2 + 2 + 2 + 3 = 9.
Example 3:
Input: nums = [7,5,9]
Output: 21
Explanation:
- There is no pair
(a, b)such thatnums[a] % nums[b] == 0. - Hence, no operation can be performed. The sum remains
7 + 5 + 9 = 21.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 105
# 初始化 数字 -> [它的因子列表] MX = 100001 mmap = [[] for _ in range(MX)] for i in range(1, MX): for j in range(i, MX, i): mmap[j].append(i) class Solution: def minArraySum(self, nums: list[int]) -> int: # 通过map groupby 统计重复数字 ncounter = Counter(nums) total = 0 for num in ncounter: for div in mmap[num]: # 如果因子在列表中 if div in ncounter: total += div * ncounter[num] break return total

浙公网安备 33010602011771号