«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every k-th dragon got punched in the face with a frying pan. Every l-th dragon got his tail shut into the balcony door. Every m-th dragon got his paws trampled with sharp heels. Finally, she threatened every n-th dragon to call her mom, and he withdrew in panic.
How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of d dragons?
Input data contains integer numbers k, l, m, n and d, each number in a separate line (1 ≤ k, l, m, n ≤ 10, 1 ≤ d ≤ 105).
Output the number of damaged dragons.
1 2 3 4 12
12
2 3 4 5 24
17
In the first case every first dragon got punched with a frying pan. Some of the dragons suffered from other reasons as well, but the pan alone would be enough.
In the second case dragons 1, 7, 11, 13, 17, 19 and 23 escaped unharmed.
其实这个题暴力很容易就ac了这里暴力方法就不说啦,说说数论解法。在离散数学中我们学过,要求a1 a2 a3 a4 在n范围内的去重后倍数的个数是有公式的,如果这四个数互素,那么结果就是 :
ans = sum(n/a[i]) - sum(n/(a[i]*a[j])) + sum(n / (a[i]*a[j]*a[k])) - sum(n /(a1*a2*a3*a4));
但是这里并非互素,其实类似,只要把里面的乘法改为求几个数的最小公倍数就好啦。这种算法将在0ms解决非常大的数据。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <cstring>
#include <map>
#include <climits>
using namespace std;
int gcd(int a,int b)
{
return b==0 ? a: gcd(b,a%b);
}
int lcm(int a,int b)
{
return (a/gcd(a,b))*b;
}
int v[5];
int n;
int main()
{
cin >> v[0] >> v[1] >> v[2] >> v[3] >> n;
int ans = 0;
for(int i = 0; i < 4; i++)
ans += n/v[i];
ans -= n/lcm(v[0],v[1]);
ans -= n/lcm(v[0],v[2]);
ans -= n/lcm(v[0],v[3]);
ans -= n/lcm(v[1],v[2]);
ans -= n/lcm(v[1],v[3]);
ans -= n/lcm(v[2],v[3]);
ans += n/lcm(v[1],lcm(v[2],v[3]));
ans += n/lcm(v[0],lcm(v[2],v[3]));
ans += n/lcm(v[0],lcm(v[1],v[3]));
ans += n/lcm(v[0],lcm(v[1],v[2]));
ans -= n/lcm(lcm(v[0],v[1]),lcm(v[2],v[3]));
cout << ans <<endl;
return 0;
}