Project Euler

Problem 29(Distinct powers)

(이경수) 2019. 5. 12. 16:48

Problem 29(Distinct powers)

Consider all integer combinations of \( a^{b} \) for \(2 \leq a \leq 5\) and \(2 \leq b \leq 5\):

\(2^{2}=4, 2^{3}=8, 2^{4}=16, 2^{5}=32\)
\(3^{2}=9, 3^{3}=27, 3^{4}=81, 3^{5}=243\)
\(4^{2}=16, 4^{3}=64, 4^{4}=256, 4^{5}=1024\)
\(5^{2}=25, 5^{3}=125, 5^{4}=625, 5^{5}=3125\)

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

4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

How many distinct terms are in the sequence generated by \(ab\) for \(2 \leq a \leq 100\) and \(2 \leq b \leq 100\)?

 

In Python:

import time

startTime = time.time()
abList = [a ** b for a in range(2, 101) for b in range(2, 101)]
print(len(set(abList)))
print(time.time() - startTime, "seconds")

Run time: 0.017004966735839844 seconds

 

In Java:

package project_euler21_30;

import java.util.HashSet;
import java.math.BigInteger;

public class Euler29 {
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		HashSet<BigInteger> abSet = new HashSet<BigInteger>();
		for (int a = 2; a < 101; a++) {
			for (int b = 2; b < 101; b++) {
				BigInteger result = BigInteger.valueOf(0);
				BigInteger num = BigInteger.valueOf(a);
				result = num.pow(b);
				abSet.add(result);
			}
		}
		System.out.println(abSet.size());
		long endTime = System.currentTimeMillis();
		System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");
	}
}

Run time: 0.057seconds

 

Solution: 9183