
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if N is a Pentagonal Number in C++
Given with a number N the task is to check whether the number is a pentagonal number or not. Numbers that can be arranged to form a pentagon is a pentagonal number as these numbers can be used as points to form a pentagon. For example, some of pentagonal numbers are 1, 5, 12, 22, 35, 51....
We can use formula to check whether the number is a pentagonal number or not
$$p(n)=\frac{\text{3}*n^2-n}{\text{2}}$$
Where, n is the number of points pentagonal will have
Example
Input-: n=22 Output-: 22 is pentagonal number Input-: n=23 Output-: 23 is not a pentagonal number
Algorithm
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
Example
#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; }
Output
22 is pentagonal
Advertisements