Project Euler/63: Difference between revisions
From charlesreid1
m (Replacing charlesreid1.com:3000 with git.charlesreid1.com) |
|||
| (2 intermediate revisions by the same user not shown) | |||
| Line 15: | Line 15: | ||
==Code== | ==Code== | ||
Link: https://charlesreid1.com | Here is the full solution method - quite simple compared to some of the other Project Euler problems in the 60s range: | ||
<pre> | |||
public static void solve() { | |||
// These are the only numbers that qualify, | |||
// since 10^n is n+1 digits | |||
int counter = 0; | |||
for(int i=1; i<10; i++) { | |||
for(int j=1; j<25; j++) { | |||
int ndigits = (int)(Math.ceil(j*Math.log10(i))); | |||
boolean jDigits = (ndigits==j); | |||
if(jDigits) { | |||
counter++; | |||
} | |||
} | |||
} | |||
// This doesn't count 0^1, which is 0, also 1 digit. | |||
counter++; | |||
System.out.println(counter); | |||
} | |||
</pre> | |||
Link: https://git.charlesreid1.com/cs/euler/src/master/scratch/Round2_050-070/063/Problem063.java | |||
==Flags== | ==Flags== | ||
{{ProjectEulerFlag}} | {{ProjectEulerFlag}} | ||
Latest revision as of 03:49, 9 October 2019
Problem Statement
How many n-digit positive integers exist which are also an nth power?
Link: https://projecteuler.net/problem=63
Solution Technique
This one is almost embarrassingly easy...
To check if a number $ a^b $ is $ b $ digits, we can take $ \log_{10}(b) $ and if the value, rounded up, is $ b $, our criteria is met.
For this particular problem, we can stop at $ n=25 $, since ceil(log10(9**25)) = 25
Code
Here is the full solution method - quite simple compared to some of the other Project Euler problems in the 60s range:
public static void solve() {
// These are the only numbers that qualify,
// since 10^n is n+1 digits
int counter = 0;
for(int i=1; i<10; i++) {
for(int j=1; j<25; j++) {
int ndigits = (int)(Math.ceil(j*Math.log10(i)));
boolean jDigits = (ndigits==j);
if(jDigits) {
counter++;
}
}
}
// This doesn't count 0^1, which is 0, also 1 digit.
counter++;
System.out.println(counter);
}
Link: https://git.charlesreid1.com/cs/euler/src/master/scratch/Round2_050-070/063/Problem063.java
Flags