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;
}输出
如果我们运行以上代码,它将生成以下输出:
Ordered pairs such that product is less than N:10
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP