计算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(intn)取n并返回乘积<n的有序对的计数
对于成对的初始变量计数为0。
使用两个for循环遍历以成对。
从i=1到i<n。并且j=1到(i*j)<n。
增量计数为1。
在所有循环结束时,计数将包含此类对的总数。
返回计数结果。
示例
#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;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Ordered pairs such that product is less than N:10