使用C++查找不能被[2, 10]范围内任何数整除的数字


在这篇文章中,我们将讨论如何找到从1到n(给定)的范围内,不能被2到10之间任何数字整除的数字。让我们通过一些例子来理解这一点:

Input : num = 14
Output : 3
Explanation: There are three numbers, 1, 11, and 13, which are not divisible.

Input : num = 21
Output : 5
Explanation: There are five numbers 1, 11, 13, 17, and 19, which are not divisible.

寻找解决方案的方法

简单方法

如果我们检查从1到num的每个数字,看它是否能被2到10之间任何数字整除。如果不能,则递增计数器。但是这种方法会花费太多时间,从而增加时间复杂度。

高效方法

我们可以想到的最佳方法是首先找到从1到num的范围内,能被[2, 10]范围内任何数字整除的数字,然后用num减去这个计数。

所以首先,我们需要找到所有能被2、3、4、5、10整除的数字。但是能被4、6、8、10整除的数字都能被2整除,能被3整除的数字都能被6和9整除。

我们需要找到所有能被2、3、5和7整除的数字。这可以通过容斥原理计算。

容斥原理

它指出,我们应该包含每个单个集合的大小,应该去除成对交集的大小,所有三个集合的交集大小应该被添加,以此类推。

查找所有数字的公式为:

= NUM – X + Y – Z + A.

其中:

X = num divisible by 2, 3, 5, 7 ( [num / 2] + [num / 3] + [num / 5] + [num / 7] )

Y = num divisible by (2,3), (2, 5), (2, 7), (3, 5), (3, 5), (3, 7) and (5, 7) = ( [num / (2 * 3)] + [num / (2 * 5)] + [num / (2 * 7)] + [num / (3 * 5)] + num / (3 * 7)] + [num / (5 * 7)] ).

Z = num divisible by (2, 3, 5), (2, 3, 7), (2, 5, 7) and (3, 5, 7) = ( [num / (2 * 3 * 5)] + [num / (2 * 3 * 7)] + [num / (2 * 5 * 7)] + [num / (3 * 5 * 7)] )

A = num divisible by (2, 3, 5, 7) = ( [num / (2 * 3 * 5 * 7)] )

示例

#include <bits/stdc++.h>
using namespace std;

int main() {
   int n = 21, result;
   // applying formula from inclusion - exclusion principle
   // to find the count of numbers not divisible by any number from 2 to 10.
   result = 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;
   cout << "The count of numbers, not div by [2, 10] is: " << result;

   return 0;
}

输出

The count of numbers, not div by [2, 10] is: 5

结论

在这篇文章中,我们讨论了如何找到从2到n范围内不能被整除的数字。为了解决这个问题,我们讨论了容斥原理。我们还讨论了C++程序,以应用该方法来获得具有O(1)复杂度的结果。你可以使用其他语言(如Java、C、Python等)编写此程序。我们希望您觉得这篇文章有帮助。

更新于:2021年11月26日

711 次浏览

开启你的职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.