How to use Brute-force Approach In C++

The idea is to first count the number of digits (or find order). Let the number of digits be order_n. For every digit curr in input number num, compute currorder_n. If the sum of all such values is equal to num, then return true, else false.

Below is the C++ program to find Armstrong numbers between 1 to 1000 using a brute force approach:

C++




// C++ program to find Armstrong numbers
// between 1 to 1000 using a brute force
// approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the order of
// a number.
int order(int num)
{
    int count = 0;
    while (num > 0)
    {
        num /= 10;
        count++;
    }
    return count;
}
 
// Function to check whether the
// given number is Armstrong number
// or not
bool isArmstrong(int num)
{
    int order_n = order(num);
    int num_temp = num, sum = 0;
 
    while (num_temp > 0)
    {
        int curr = num_temp % 10;
        sum += pow(curr, order_n);
        num_temp /= 10;
    }
    if (sum == num)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
// Driver code
int main()
{
 
    cout << "Armstrong numbers between 1 to 1000 : ";
    // Loop which will run from 1 to 1000
    for (int num = 1; num <= 1000; ++num)
    {
 
        if (isArmstrong(num))
        {
            cout << num << " ";
        }
    }
    return 0;
}


Output

Armstrong numbers between 1 to 1000 : 1 2 3 4 5 6 7 8 9 153 370 371 407 

Time Complexity: O(n*d), where d is the order of a number and n is the range(1, 1000).
Auxiliary Space: O(1).

C++ Program to Print Armstrong Numbers Between 1 to 1000

Here, we will see how to print Armstrong numbers between 1 to 1000 using a C++ program. 

Similar Reads

Armstrong Number

A number “N” is an Armstrong number if “N” is equal to the sum of all N’s digits raised to the power of the number of digits in N....

1. Using Brute-force Approach

The idea is to first count the number of digits (or find order). Let the number of digits be order_n. For every digit curr in input number num, compute currorder_n. If the sum of all such values is equal to num, then return true, else false....

2. Using Optimized Solution

...