Explanation
We can identify that given any integer , the number of integers that are divisible by it between 1 and is
If we consider each prime individually and find the number of multiples it has, we will find that there is an overlap for each number that is a multiple of two primes. For example, is a multiple of both and , so if we added up all for all primes, we would still need to subtract for all distinct i and j.
Similarly, this subtraction would have an overlap for each number that is a multiple of three primes. An example would be , a multiple of , , and , so we would have subtracted all multiples of both , , and , which would mean that we must add back the number of integers that are multiples of three primes. This extends for the entire array, requiring us to alternate adding and subtracting depending on how many primes we are currently multiplying.
Considering only , the full example would be that our answer is added times for , , and (subsets of array with prime), then subtracted times for , , and (subsets of array with primes), and finally added once for (subset of array with primes), overall only being counted once.
To implement this, we would need to go through each subset of the array, and add the number of multiples it has if the number of primes is not divisible by 2, and subtract otherwise. This is known as the Inclusion Exclusion Principle. In order to iterate through all subsets of the array, we can iterate from to and use bit operators to find which indices we are using.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;typedef long long ll;int main() {ll n, k;cin >> n >> k;vector<ll> a(k);for (int i = 0; i < k; i++) cin >> a[i];
Java
import java.util.*;public class PrimeMultiples {public static void main(String[] args) {Scanner sc = new Scanner(System.in);long n = sc.nextLong();int k = sc.nextInt();long[] a = new long[k];for (int i = 0; i < k; i++) { a[i] = sc.nextLong(); }
Python
Warning!
Due to Python's big constant factor, this code will TLE on a couple of test cases.
n, k = map(int, input().split())a = list(map(int, input().split()))ans = 0for i in range(1, 1 << k):prime_product = 1for j in range(k):# check if we are using a[j] in this numberif i & (1 << j):
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!