I have an integer 153
, and I need to determine whether or not he is equal to the sum of pow(digit, digits). so 153 = 1^3 + 5^3 + 3^3 = 153
returns true
.
I chose to find the number of digits using a basic loop, then pushing all the integers into a vector so I could use the std::for_each
function to iterate and use pow()
on each of the elements.
The problem I am facing is the changing of each element. I don't want to resort to a for
-loop yet, but I can't seem to figure out how to do it via the for_each
.
Errors are commented in the code.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <numeric>
bool narcissistic(int value)
{
int k{};
std::vector <int> sum{};
while (value > 0) {
k++;
sum.push_back(value % 10);
value /= 10;
}
std::for_each(sum.begin(), sum.end(), [](int& n) {pow(n, k); }); // error: 'k' is not captured
// (warning) note: the lambd has no capture-default
if (std::accumulate(sum.begin(), sum.end(), 0) == value) return true;
return false;
}
int main()
{
std::cout << narcissistic(153) << std::endl;
return 0;
}