C++ 中查找积小于 N 的有序对


给定一个数字 N。目标是找到正数的有序对,使得它们的乘积小于 N。

我们将从 i=1 到 i<N 和 j=1 到 (i*j)<N 开始。然后递增计数。

让我们通过示例来理解。

输入 

N=4

输出 

Ordered pairs such that product is less than N:5

解释 

Pairs will be (1,1) (1,2) (1,3) (2,1) (3,1)

输入 

N=100

输出 

Ordered pairs such that product is less than N: 473

解释 

Pairs will be (1,1) (1,2) (1,3)....(97,1), (98,1), (99,1). Total 473.

下面程序中使用的方案如下

  • 我们取整数 N。

  • 函数 productN(int n) 取 n 并返回积 < n 的有序对的数量

  • 将初始变量 count 设为 0 以表示对。

  • 使用两个 for 循环遍历以构成对。

  • 从 i=1 到 i<n 开始。以及 j=1 到 (i* j)<n。

  • 将 count 增加 1。

  • 在所有循环结束时,count 将包含此类对的总数。

  • 返回 count 作为结果。

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
int productN(int n){
   int count = 0;
   for (int i = 1; i < n; i++){
      for(int j = 1; (i*j) < n; j++)
         { count++; }
   }
   return count;
}
int main(){
   int N = 6;
   cout <<"Ordered pairs such that product is less than N:"<<productN(N);
   return 0;
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

如果我们运行以上代码,它将生成以下输出:

Ordered pairs such that product is less than N:10

更新于: 2020-10-31

94 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告