Stella Octangula Numbers in C++
In this article, we will discuss the Stella Octangula Numbers in C++ with its different approaches.
Introduction
Stella Octangula numbers, a type of figurate number, are derived from the geometric shape Stella Octangula (eight-pointed star). These numbers follow the formula n(2n² - 1), where n is a non-negative integer. The first few Stella Octangula numbers are:
0, 1, 14, 51, 124, 245, 426, 679, 1016, 1449, ...
This tutorial guides us through creating C++ code to check if a given number is a Stella Octangula number. We'll explore two approaches:
To check if a given number is a Stella Octangula number. We'll explore two approaches:
1. Iterative Approach
2. Improved Iterative Approach (with Optimization)
Approach 1. Iterative Approach
This straightforward approach iterates through potential values of n, calculating n(2n² - 1) at each step and comparing it to the given number:
#include <iostream>
using namespace std;
bool isStellaOctangula(int x) {
for (int n = 0; n * (2 * n * n - 1) <= x; n++) {
if (n * (2 * n * n - 1) == x) {
return true;
}
}
return false;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isStellaOctangula(number)) {
cout << number << " is a Stella Octangula number." << endl;
} else {
cout << number << " is not a Stella Octangula number." << endl;
}
return 0;
}
Output:
![Stella Octangula Numbers in C++/>
<!-- /wp:html -->
<!-- wp:heading -->
<h2 class=](https://static.tutorialandexample.com/cpp/stella-octangula-numbers-in-cpp1.png)
While the iterative approach is simple, it can be inefficient for large x values. This version improves efficiency by taking larger steps in the n values:
#include <iostream>
using namespace std;
bool isStellaOctangulaOptimized(int x) {
int n = 0;
// Find the closest n such that n * (2 * n * n - 1) is less than or equal to x
while (n * (2 * n * n - 1) < x) {
n++;
}
// Check if x is equal to n * (2 * n * n - 1)
return (n * (2 * n * n - 1) == x);
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (isStellaOctangulaOptimized(number)) {
cout << number << " is a Stella Octangula number." << endl;
} else {
cout << number << " is not a Stella Octangula number." << endl;
}
return 0;
}
Output:
![Stella Octangula Numbers in C++/>
<!-- /wp:html -->
<!-- wp:html -->
<div class=](https://static.tutorialandexample.com/cpp/stella-octangula-numbers-in-cpp2.png)