Skip to content

Instantly share code, notes, and snippets.

@zhugw
Last active May 16, 2017 14:46
Show Gist options
  • Save zhugw/50587c51c067e4a16301de2f8078230e to your computer and use it in GitHub Desktop.
Save zhugw/50587c51c067e4a16301de2f8078230e to your computer and use it in GitHub Desktop.
Pow_a_b_efficiently
package interview;
import org.junit.Test;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.Assert.assertEquals;
/**
* efficiently implement a^b
* Created by zhuguowei on 5/16/17.
*/
public class Pow {
private static final ConcurrentHashMap<String,Long> cache = new ConcurrentHashMap();
// private static final HashMap<String,Long> cache = new HashMap();
public long pow(long a, long b){
System.out.printf("%d ^ %d%n",a,b);
if(b == 1L){
return a;
}
if( b == 2L){
return a*a;
}
long l = b/2;
long r = b - l;
return cache.computeIfAbsent(a+","+l,k->pow(a,l)) * cache.computeIfAbsent(a+","+r,k->pow(a,r));
}
@Test
public void testPow(){
long result = pow(2, 30);
assertEquals(Math.pow(2,30),result*1.0,0);
}
public long pow2(final long a, final long b){
// return LongStream.range(0, b).parallel().reduce(1, (acc, x) -> a * acc);
return Collections.nCopies((int)b,a).parallelStream().reduce(1L, (acc, x) -> acc * x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment