You can solve it in O(log n)
.
For example, for n = 1234 = 10011010010 (in base 2) we have n = 2 + 16 + 64 + 128 + 1024 and, therefore, 2 ^ n = 2 ^ 2 * 2 ^ 16 * 2 ^ 64 * 2 ^ 128 * 2 ^ 1024.
Note that 2 ^ 1024 = (2 ^ 512) ^ 2, so if you know 2 ^ 512, you can calculate 2 ^ 1024 in a couple of operations.
The solution will be like this (pseudo-code):
const ulong MODULO = 1000000007; ulong mul(ulong a, ulong b) { return (a * b) % MODULO; } ulong add(ulong a, ulong b) { return (a + b) % MODULO; } int[] decompose(ulong number) {
Note that O(log n)
in practice O(1)
for ulong
arguments (like log n <63); and that this code is compatible with any uint
MODULO (MODULO <2 ^ 32), regardless of whether MODULO is simple or not.
source share