Calculate Exponents bit by bit
JavaScript (ES7), 55 bytes
f=(a,b,c=2)=>b>1?b%c?f(a,b,c+1):a+['^'+b,f(a**c,b/c)]:a
Uses ,
in place of =
(2^15,8^5,32768
).
Test cases
f=(a,b,c=2)=>b>1?b%c?f(a,b,c+1):a+['^'+b,f(Math.pow(a,c),b/c)]:a
g=(a,b)=>console.log(`f(${a}, ${b}):`,f(a,b))
g(4,8)
g(5,11)
g(2,15)
Note: the snippet uses Math.pow
instead of **
for cross-browser compatibility.
05AB1E, 23 22 17 bytes
Saved 5 bytes by noticing the flexible output format.
Ò©gƒ²®N¹‚£P`Šm‚Rˆ
Try it online!
Explanation
Example for 2^15
Ò© # calculate primefactors of exponent and store in register
# STACK: [3,5]
g # length
# STACK: 2
ƒ # for N in range[0 ... len(primefactors)] do
² # push base
# STACK: 2
® # push primefactors
# STACK: 2, [3,5]
N¹‚£ # split into 2 parts where the first is N items long
# 1st, 2nd, 3rd iteration: [[], [3, 5]] / [[3], [5]] / [[3, 5], []]
P # reduce each by product
# STACK 1st iteration: 2, [1,15]
` # split list to items on stack
# STACK 1st iteration: 2, 1, 15
Š # move down the current exponent
# STACK 1st iteration: 15, 2, 1
m # raise base to the rest of the full exponent
# STACK 1st iteration: 15, 2
‚ # pair them up
# STACK 1st iteration: [15,2]
R # reverse the pair
# STACK 1st iteration: [2,15]
ˆ # store it in global list
# print global list at the end of execution
Jelly, 16 bytes
*Uż:Ṫ
ÆfṪ1;×\ç@€
Try it online!
Input is a single list [base, exponent]
. The return value of the lower monadic link is a list of lists, as a full program a representation of that list is printed, for example 2^15=8^5=32768^1
is printed as:
[[2, 15], [8, 5], [32768, 1]]
How?
ÆfṪ1;×\ç@€ - Main link: [base, exponent] e.g. [4,12]
Æf - prime factorization array (vectorises) [[2,2],[2,2,3]]
Ṫ - tail (tailing first costs bytes) [2,2,3]
1; - 1 concatenated with the result [1,2,2,3]
×\ - reduce with multiplication (make factors) [1,2,4,12]
ç@€ - call last link (1) as a dyad for €ach with reversed @rguments
- implicit print if running as a full program
*Uż:Ṫ - Link 1, an entry in the equality: [base, exponent], factor e.g. [4, 12], 4
* - exponentiate (vectorises) : [base ^ factor, exponent ^ factor] [256, 20736]
U - upend [20736, 256]
: - integer division: [base // factor, exponent // factor] [1, 3]
ż - zip [[20736, 1], [256, 3]]
Ṫ - tail [256, 3]
...i.e at a factor of 4: 4 ^ 12 = 256 ^ 3
It could be formatted as a grid for 2 bytes by a trailing µG
, e.g.:
2 15
8 5
32768 1
...or fully formatted, including trimming off the ^1
, for 9, with a trailing j€”^j”=ṖṖ
, e.g.:
2^15=8^5=32768