给定数字N,任务是检查数字是否为五角形。可以排列成五边形的数字是五边形数字,因为这些数字可以用作形成五边形的点。例如,一些五角数是1、5、12、22、35、51...。
我们可以使用公式来检查数字是否为五角形
$$p(n)= \ frac {\ text {3} * n ^ 2-n} {\ text {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; //检查N是否为五边形。 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