A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another
integer multiplied by k. For example for k = 2, {1,3,4} is a valid set, but not {2,4,5}, as 4 is double of 2.
You will be given n and k. you have to determine the largest k-multiple free subset of the integers from 1 to n.
Input
First line of the input contains T (1 ≤ T ≤ 1000) the number of test case. Then following lines contains T test cases. Each case contains a line containing 2 integers n (1 ≤ n ≤ 1000000000) and k (2 ≤ k ≤ 100).
Output
For each test case output contains 1 integer the size of the largest k-multiple free subset of the integers from 1 to n.
Sample Input
3
10 2
100 2
1000 2
Sample Output
6
67
666
问题链接:UVA11246 K-Multiple Free set
问题简述:一个{1…n}的集合,计算其子集合,使得元素个数最多,并且不存在有两个元素x1 * k = x2,求出最多的元素个数是多少?
问题分析:
开始时子集有n个元素,先删除k倍的,删除为{k, 2k, 3k, 4k, 5k, 6k…},会删掉多余的k2,因此需要再加回k2倍的数。这时候会出现多出k2的情况,如迭代下去,得到最后答案为n - n / k + n / (k ^ 2) - n / (k ^ 3) + n / (k ^ 4)…。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++语言程序如下:
/* UVA11246 K-Multiple Free set */
#include <bits/stdc++.h>
using namespace std;
int solve(int n, int k)
{
int sign = 1, ans = 0;
while (n) {
ans += sign * n;
n /= k;
sign = - sign;
}
return ans;
}
int main()
{
int t, n, k;
scanf("%d", &t);
while(t--) {
scanf("%d%d", &n, &k);
printf("%d\n", solve(n, k));
}
return 0;
}