เราได้รับหมายเลข N เป้าหมายคือการหาคู่ที่สั่งซื้อของจำนวนบวกซึ่งผลิตภัณฑ์ของพวกเขามีค่าน้อยกว่า N
เราจะทำสิ่งนี้โดยเริ่มจาก i=1 ถึง i
มาทำความเข้าใจกับตัวอย่างกัน
ป้อนข้อมูล
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 และส่งกลับจำนวนคู่ที่สั่งซื้อกับผลิตภัณฑ์
-
ใช้ตัวแปรเริ่มต้นนับเป็น 0 สำหรับคู่
-
สำรวจโดยใช้สองลูปเพื่อสร้างคู่
-
เริ่มจาก i=1 ถึง i
-
นับเพิ่มขึ้นทีละ 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