ให้ตัวเลข N ต้องตรวจสอบว่าเป็นเลข Pentagon (Pentagonal Number) หรือไม่ เลขที่สามารถจัดเรียงเป็นรูปห้าเหลี่ยมได้ เรียกว่าเลข Pentagon เนื่องจากสามารถใช้เป็นจุดสร้างรูปห้าเหลี่ยมได้ ตัวอย่างเลข Pentagon คือ 1, 5, 12, 22, 35, 51...
เราสามารถใช้สูตรตรวจสอบได้
$$p(n)=\frac{3n^2-n}{2}$$
โดย n คือจำนวนจุดของรูปห้าเหลี่ยม
ตัวอย่าง
Input-: n=22 Output-: 22 is pentagonal number Input-: n=23 Output-: 23 is not a pentagonal number
อัลกอริทึม
Start Step 1 -> declare function to Check N is pentagonal or not bool check(int n) declare variables as int i = 1, a do set a = (3*i*i - i)/2 set i += 1 while ( a < n ); return (a == n); Step 2 -> In main() Declare int n = 22 If (check(n)) Print is pentagonal End Else Print it is not pentagonal End Stop
ตัวอย่าง
#include <iostream> using namespace std; // check N is pentagonal or not. bool check(int n){ int i = 1, a; do{ a = (3*i*i - i)/2; i += 1; } while ( a < n ); return (a == n); } int main(){ int n = 22; if (check(n)) cout << n << " is pentagonal " << endl; else cout << n << " is not pentagonal" << endl; return 0; }ผลลัพธ์
22 is pentagonal