Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
Not able to solve the power sum for all cases using recursion

I have written the code of this problem but it works for only 70% of the test cases. I can't figure out what is wrong with it. Please help.

Problem:- Find the number of ways that a given integer, X, can be expressed as the sum of the Nth powers of unique, natural numbers in the range of [1,25] both inclusive.

Hint:-

The answer will be (1^2 + 3^2).

My code is not working for x = 100 and n = 2. The output should be 3 but it returns 33.

let x = 100;
let n = 2;
let num = 0;
let index = 1;

function power(x, n, num, index, ways = 0) {
  if (x === num) {
    return 1;
  }
  if (x < num) {
    return 0;
  }
  for (let i = index; i <= 25; i++) {
    ways += power(x, n, (num + ((i) ** n)), index + 1);
  }
  return ways;
}
console.log(power(x, n, num, index));

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your logic is almost right. But you're not properly removing duplicate values and ending up including things like 9^2 + 3^2 + 3^2 + 1^2 or 5^2 + 5^2 + 5^2 + 4^2 + 3^2.

You need to change the recursive index you pass. You shouldn't use your index parameter but your loop iterator, i:

let x = 100;
let n = 2;
let num = 0;
let index = 1;

function power(x, n, num, index, ways = 0) {
  if (x === num) {
    return 1;
  }
  if (x < num) {
    return 0;
  }
  for (let i = index; i <= 25; i++) {
 // ways += power(x, n, (num + ((i) ** n)), index + 1);
 //                                         v-^
    ways += power(x, n, (num + ((i) ** n)), i + 1);
  }
  return ways;
}
console.log(power(x, n, num, index));

I figured this out fairly quickly by writing my own version of the function from scratch, and getting the exact same wrong result. I added some logging and realized the problem and was able to spot it quickly. This translated easily to your code.

But I think my function is cleaner, so I'm including it here. It does much the same logic, but in a cleaner functional manner:

const range = (lo, hi) => 
  Array .from ({length: hi - lo + 1}, (_, i) => i + lo)

const sum = (ns) =>
  ns .reduce ((a, b) => a + b, 0)

const countPowerSums = (n, p, i = 1) =>
  n < 0
    ? 0
  : n == 0
    ? 1
  : sum (range (i, 25) .map (b => countPowerSums (n - b ** p, p, b + 1)))

console .log (countPowerSums (100, 2))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda