Own digits power sum: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (Minor code improvement.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
(2 intermediate revisions by one other user not shown)
Line 467:
<pre>
Same as before.
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
#include <cmath>
#include <cstdint>
#include <iostream>
#include <vector>
 
int main() {
std::vector<uint32_t> powers = { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 };
 
std::cout << "Own digits power sums for N = 3 to 9 inclusive:" << std::endl;
 
for ( uint32_t n = 3; n <= 9; ++n ) {
for ( uint32_t d = 2; d <= 9; ++d ) {
powers[d] *= d;
}
 
uint64_t number = std::pow(10, n - 1);
uint64_t maximum = number * 10;
uint32_t last_digit = 0;
uint32_t digit_sum = 0;
 
while ( number < maximum ) {
if ( last_digit == 0 ) {
digit_sum = 0;
uint64_t copy = number;
while ( copy > 0 ) {
digit_sum += powers[copy % 10];
copy /= 10;
}
} else if ( last_digit == 1 ) {
digit_sum++;
} else {
digit_sum += powers[last_digit] - powers[last_digit - 1];
}
 
if ( digit_sum == number ) {
std::cout << number << std::endl;
if ( last_digit == 0 ) {
std::cout << number + 1 << std::endl;
}
number += 10 - last_digit;
last_digit = 0;
} else if ( digit_sum > number ) {
number += 10 - last_digit;
last_digit = 0;
} else if ( last_digit < 9 ) {
number++;
last_digit++;
} else {
number++;
last_digit = 0;
}
}
}
}
</syntaxhighlight>
{{ out }}
<pre>
Own digits power sums for N = 3 to 9 inclusive:
153
370
371
407
1634
8208
9474
54748
92727
93084
548834
1741725
4210818
9800817
9926315
24678050
24678051
88593477
146511208
472335975
534494836
912985153
</pre>
 
Line 1,014 ⟶ 1,098:
long maximum = number * 10;
int lastDigit = 0;
int digitSumsum = 0;
while ( number < maximum ) {
if ( lastDigit == 0 ) {
digitSumsum = String.valueOf(number).chars()
.chars().map(Character::getNumericValue).map( i -> powers.get(i) ).sum();
.map( i -> powers.get(i) )
.sum();
} else if ( lastDigit == 1 ) {
digitSumsum += 1;
} else {
digitSumsum += powers.get(lastDigit) - powers.get(lastDigit - 1);
}
if ( digitSumsum == number ) {
System.out.println(number);
if ( lastDigit == 0 ) {
Line 1,035 ⟶ 1,117:
number += 10 - lastDigit;
lastDigit = 0;
} else if ( digitSumsum > number ) {
number += 10 - lastDigit;
lastDigit = 0;
Line 2,253 ⟶ 2,335:
{{libheader|Wren-math}}
Includes some simple optimizations to try and quicken up the search. However, getting up to N = 9 still took a little over 4 minutes on my machine.
<syntaxhighlight lang="ecmascriptwren">import "./math" for Int
 
var powers = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Line 2,322 ⟶ 2,404:
{{libheader|Wren-seq}}
Astonishing speed-up. Runtime now only 0.5 seconds!
<syntaxhighlight lang="ecmascriptwren">import "./seq" for Lst
 
var maxBase = 10
9,476

edits