Project-Euler-029

Problem

Consider all integer combinations of $a^b$ for $2 \leq a \leq 5$ and $2 \leq b \leq 5$:

$$\begin{aligned}
& 2^2 = 4\text{, } 2^3 = 8\text{, } 2^4 = 16\text{, } 2^5 = 32 \
& 3^2 = 9\text{, } 3^3 = 27\text{, } 3^4 = 81\text{, } 3^5 = 243 \
& 4^2 = 16\text{, } 4^3 = 64\text{, } 4^4 = 256\text{, } 4^5 = 1024 \
& 5^2 = 25\text{, } 5^3 = 125\text{, } 5^4 = 625\text{, } 5^5 = 3125
\end{aligned}$$

If they are then placed in numerical order, with any repeats removed, we
get the following sequence of 15 distinct terms:

$$4\text{, } 8\text{, } 9\text{, } 16\text{, } 25\text{, } 27\text{, } 32\text{, } 64\text{, } 81\text{, } 125\text{, } 243\text{, } 256\text{, } 625\text{, } 1024\text{, } 3125$$

How many distinct terms are in the sequence generated by $a^b$ for
$2 \leq a \leq 100$ and $2 \leq b \leq 100$?

Answer

1
9183

Python

1
2
3
#!/usr/bin/env python
import itertools
print(len(set(a**b for a,b in itertools.product(list(range(2,101)), repeat=2))))

Ruby

1
2
#!/usr/bin/env ruby
puts (2..100).to_a.product((2..100).to_a).map { |a,n| a**n }.uniq.count

Haskell

1
2
3
4
import Data.List (nub)

main :: IO ()
main = print $ length $ nub [a^n | a <- [2..100], n <- [2..100]]

Mathematica

1
2
3
4
5
(* 
* We generate all possible powers in the given range, put the values in a flat list,
* delete the duplicates of any value, and count the length of the remaining list.
*)
Length[Union[Flatten[Table[a^b, {a, 2, 100}, {b, 2, 100}]]]]

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;


public final class p029 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p029().run());
}


/*
* We generate all the possible powers in the given range, put each value
* into a set, and let the set count the number of unique values present.
*/
public String run() {
Set<BigInteger> generated = new HashSet<>();
for (int a = 2; a <= 100; a++) {
for (int b = 2; b <= 100; b++)
generated.add(BigInteger.valueOf(a).pow(b));
}
return Integer.toString(generated.size());
}

}
文章作者: Monad Kai
文章链接: onlookerliu.github.io/2018/04/13/Project-Euler-029/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Code@浮生记
支付宝打赏
微信打赏