标签:lcm
The least common multiple (denoted "lcm") of a non-empty sequence of positive integers is the smallest positive integer that is divisible by each of them. For example, lcm(2)=2, lcm(4,6)=12, and lcm(1,2,3,4,5)=60.
Alice had a positive integer N. Then she chose some positive integer M that was strictly greater than N. Afterwards, she computed two values: the value A = lcm(N+1, N+2, ..., M) and the value B = lcm(1, 2, ..., M). She was surprised when she saw that A = B.the value A = lcm(N+1, N+2, ..., M) and the value B = lcm(1, 2, ..., M). She was surprised when she saw that A = B.the value A = lcm(N+1, N+2, ..., M) and the value B = lcm(1, 2, ..., M). She was surprised when she saw that A = B.the value A = lcm(N+1, N+2, ..., M) and the value B = lcm(1, 2, ..., M). She was surprised when she saw that A = B.the value A = lcm(N+1, N+2, ..., M) and the value B = lcm(1, 2, ..., M).
You are given the int N. Find and return the smallest M Alice could have chosen. (Such an M will always exist.)
In this problem the actual LCM values used can be notably large. It is best to avoid approaches that calculate them directly. Then how about we think of this problem in terms of the prime factorization of the numbers. For example, consider two numbers: 12 and
135. Their prime factorizations are:
We need to translate this into distinct conditions, one for each relevant prime number:
Where
What happens here is we take advantage that the maximum operation is associative. This means
We want
There must be a number
Did you notice that in the examples it initially appears that the result is always
For each prime
For each prime number we need to find
vector<int> get_primes(int N) { // Sieve of Erathostenes to find all the necessary prime numbers: vector<int> res; vector<bool> composite(N + 1, false); for (int p = 2; p <= N; p++) { if (! composite[p]) { for (int i = p+p; i <= N; i += p) { composite[i] = true; } res.push_back(p); } } return res; } int get_exponent(int x, int p) { int r = 0; while (x % p == 0) { r++; x /= p; } return r; } int getMin(int N) { int res = 2; // For each prime number <= N: for (int p: get_primes(N) ) { // first find the maximum exponent of p among numbers <= N // (in the explanation , this max_exp is c) int max_exp = 0; int i = p; while (i <= N) { max_exp = std::max(max_exp, get_exponent(i,p) ); i += p; } // seek the minimum i such that get_exponent(i,p) >= max_exp: while (get_exponent(i,p) < max_exp) { i += p; } // the maximum for all ps is the result: res = std::max(res, i); } return res; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
最小公倍数 SRM 661 Div1 250: MissingLCM
标签:lcm
原文地址:http://blog.csdn.net/acm_10000h/article/details/47072583