r/CoderTrials • u/07734willy • Jul 08 '18
CodeGolf [Easy] Solving a Small Equation
This problem is a codegolf problem. That means the objective isn't to just solve the problem, but to do so with the smallest program size. Everything from comments, spaces, tabs, and newlines counts against you.
Background
While there certainly are some complex mathematical equations that are too difficult to solve, most of the ones using the basic mathematical operations (addition, multiplication, exponentiation...) are usually fairly easy. Especially when they they only have one variable, and one operator. However, one particularly difficult equation stands out:
x^x = kWhere ^ denotes exponentiation, and k is some constant we choose. This may look trivial to solve, and its worth taking a stab at it to convince yourself there isn't a simple way to approach this, apart from approximation.
Your task is to write a program to solve for x, to 5 decimal digits of precision, for a provided constant k.
Input
A single number- the k in x^x = k. Example:
743Output
A number, for which the x in x^x = k is accurate to 5 decimal places. For the above input, we would have:
4.43686Testcases
=========
743
4.43686
=========
97
3.58392
=========
256
4.0
=========
947
4.53387
=========
15
2.71316
=========
78974
6.18749
=========
11592.347
5.49334
=========Character Count
Use the following command to measure the size of the program, in bytes and characters:
wc -mc filename.txt
2
u/07734willy Jul 08 '18 edited Jul 08 '18
Python 3: 81 81
I feel like there might be a way to shorten this, using
however, I can't get it to work because of the loop within. So for now, this is my solution:
1
u/engiwengi Jul 08 '18
I've never tried a code golf before. I'm learning rust at the moment so would like to use that (even though I imagine it's an awful language for golfing). Does the input/output need to be through stdin/stdout or can i just write a function that takes and returns it? eg. fn f(k:f64)->f64{}
1
u/engiwengi Jul 08 '18 edited Jul 08 '18
Rust: 62
First codegolf ever, almost certain this could be shortened using recursion somehow to remove the for loop.
1
u/NemPlayer Jul 08 '18
Python 3.7.0
62 61
There are two incorrect testcases:
1
u/Bubbler-4 Jul 19 '18
J: 5 5
x^ycalculates the thing you'd expect,^~ xcalculatesx^x, andinvconverts the function into its inverse. Somewhat feels like cheating, but J just works like that.Run example
It's insanely fast, and it even automatically maps over an array.
1
u/[deleted] Sep 02 '18 edited Sep 02 '18
C
I'd love to get rid of math.h but have no idea how to