-3

Define f(0)=1 and f(n) to be the number of different ways n can be expressed as a sum of integer powers of 2 using each power no more than twice.For example, f(10)=5 since there are five different ways to express 10:

  1. 1+1+8
  2. 1+1+4+4
  3. 1+1+2+2+4
  4. 2+4+4
  5. 2+8

what is f(n) for a given n.you can use any computer language.,

import math
def powOfTwo(n):
    i=0
    while(pow(2,i)<=n):
        if (pow(2,i)==n):
            return True
        else:
            i=i+1
    return False

def noWays(n):   
    if n==1:
        return 1
    elif n==0:
        return 0
    else:
        if (n%2==0):
            if (powOfTwo(n-2) and n-2!=2):                
                return (1+noWays((n-2)/2)+noWays(n/2))
            else:
                return (noWays((n-2)/2)+noWays(n/2))
        else:
            if (powOfTwo(n-1)and n-1!=2):
                return (1+noWays((n-1)/2))
            else:
                return (noWays((n-1)/2))
n=int(input())
v=noWays(n)
print(v)
rajiv das
  • 1
  • 2

1 Answers1

1

Often, with these kinds of puzzles, you just have to ask the question a different way.

Given a starting number, how many ways can you transform it to zero by subtracting powers of two? You can subtract each number zero, one, or two times.

Make the function signature take the following parameters:

  • n: the number you're trying to transform to zero
  • p: the minimum number you're allowed to subtract

The algorithm would look like the following. (in Typescript)

function pathsToZero(n: number, p:number) : number {
     if(n === 0) {
        // We've hit the target!
        return 1;
     }
     if(n < p) {
        // This will only be negative. No point in continuing
        return 0;
     }
     return pathsToZero(n, p*2) + pathsToZero(n-p, p*2) + pathsToZero(n-p*2, p*2);
} 


let resultForTen = pathsToZero(10, 1);
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205