📌  相关文章
📜  不能被[2,10]范围内的任何数字整除的数字

📅  最后修改于: 2021-04-26 18:52:22             🧑  作者: Mango

给定整数N。任务是找到从1N的所有数字的计数,这些数字不能被[2,10]范围内的任何数字整除。

例子:

方法:1n的总数不能被210的任何数整除等于n减去可以被210的某些数整除的数。

可被210整除的数集可以作为1n可被2整除的数集,可被3整除的数集的并集,依此类推,直到10

注意,可被468整除的数字集是可被2整除的数字集的子集,可被69可整除的数字集是可被3整除的数字集的子集。因此,无需将9个集合组合在一起,仅将2个,3个,5个和7个集合组合在一起就足够了。

所述一组数中的从1n整除的大小为2,3,5,7可使用容斥原理,说应添加各单组的该大小,成对交叉点的大小应减去的大小来计算应添加三个集合的所有交集,依此类推。

1n可被2整除的数字集的大小等于⌊n/2⌋ ,从1n可被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