给定整数N。任务是找到从1到N的所有数字的计数,这些数字不能被[2,10]范围内的任何数字整除。
例子:
Input: N = 12
Output: 2
1, 11 are the only numbers in range [1, 12] which are not divisible by any number from 2 to 10
Input: N = 20
Output: 5
方法:从1到n的总数不能被2到10的整数除尽等于n减去可以被2到10的整数除数的数。
可被2到10整除的数集可以作为1到n可被2整除的数集,可被3整除的数集的并集,依此类推,直到10 。
注意,可被4或6或8整除的数字集是可被2整除的数字集的子集,可被6或9可整除的数字集是可被3整除的数字集的子集。因此,无需将9个集合组合在一起,仅将2个,3个,5个和7个集合组合在一起就足够了。
所述一组数中的从1到n整除的大小为2,3,5,7可使用容斥原理,说应添加各单组的该大小,成对交叉点的大小应减去的大小来计算应添加三个集合的所有交集,依此类推。
从1到n可被2整除的数字集的大小等于⌊n/2⌋ ,从1到n可被2和3整除的数字集的大小等于⌊n/(2 * 3) ⌋ ,依此类推。
因此,公式为n –⌊n/2⌋–⌊n/3⌋–⌊n/5⌋–⌊n/7⌋+⌊n/(2 * 3)] +⌊n/(2 * 5)] +⌊n/(2 * 7)] +⌊n/(3 * 5)] +⌊n/(3 * 7)] +⌊n/(5 * 7)] –⌊n/(2 * 3 * 5 )] –⌊n/(2 * 3 * 7)] –⌊n/(2 * 5 * 7)] –⌊n/(3 * 5 * 7)] +⌊n/(2 * 3 * 5 * 7 )]
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count of numbers
// from 1 to N which are not divisible by
// any number in the range [2, 10]
int countNumbers(int n)
{
return n - n / 2 - n / 3 - n / 5 - n / 7
+ n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35
- n / 30 - n / 42 - n / 70 - n / 105 + n / 210;
}
// Driver code
int main()
{
int n = 20;
cout << countNumbers(n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the count of numbers
// from 1 to N which are not divisible by
// any number in the range [2, 10]
static int countNumbers(int n)
{
return n - n / 2 - n / 3 - n / 5 - n / 7
+ n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35
- n / 30 - n / 42 - n / 70 - n / 105 + n / 210;
}
// Driver code
public static void main (String[] args)
{
int n = 20;
System.out.println(countNumbers(n));
}
}
// This code is contributed by mits
Python3
# Python3 implementation of the approach
# Function to return the count of numbers
# from 1 to N which are not divisible by
# any number in the range [2, 10]
def countNumbers(n):
return (n - n // 2 - n // 3 - n // 5 - n // 7 +
n // 6 + n // 10 + n // 14 + n // 15 +
n // 21 + n // 35 - n // 30 - n // 42 -
n // 70 - n // 105 + n // 210)
# Driver code
if __name__ == '__main__':
n = 20
print(countNumbers(n))
# This code contributed by Rajput-Ji
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the count of numbers
// from 1 to N which are not divisible by
// any number in the range [2, 10]
static int countNumbers(int n)
{
return n - n / 2 - n / 3 - n / 5 - n / 7
+ n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35
- n / 30 - n / 42 - n / 70 - n / 105 + n / 210;
}
// Driver code
static void Main()
{
int n = 20;
Console.WriteLine(countNumbers(n));
}
}
// This code is contributed by mits
PHP
5
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。