Codewars挑战的解决方案速度太慢。

huangapple go评论63阅读模式
英文:

Codewars challenge solution is too slow

问题

你可以尝试使用数学方法来加速解决这个问题。这是一个求等差数列和的问题,你可以使用以下公式来计算:

n^3 + (n-1)^3 + (n-2)^3 + ... + 1^3 = (n * (n + 1) / 2)^2

你可以将这个公式用于给定的 m,然后解出 n。如果解存在,返回 n;否则返回 -1。

以下是修改后的代码:

import math

def find_nb(m):
    n = int(math.sqrt(math.sqrt(2 * math.sqrt(m)))
    if (n * (n + 1) / 2) ** 2 == m:
        return n
    else:
        return -1

print(find_nb(135440716410000))

这个方法应该比你之前的循环更快,因为它直接计算了结果而不需要遍历。

英文:

The challenge is like so:

Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n3 n^3 n3, the cube above will have volume of (n−1)3 (n-1)^3 (n−1)3 and so on until the top which will have a volume of 13 1^3 13.

You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?

The parameter of the function findNb (find_nb, find-nb, findNb, ...) will be an integer m and you have to return the integer n such as n3+(n−1)3+(n−2)3+...+13=m n^3 + (n-1)^3 + (n-2)^3 + ... + 1^3 = m n3+(n−1)3+(n−2)3+...+13=m if such a n exists or -1 if there is no such n.
Examples:

findNb(1071225) --> 45

findNb(91716553919377) --> -1

I have solved as follows, but its too slow. Is there a way to make it faster?

def find_nb(m):
    n = 0
    x = 0
    while x < m:
        n += 1
        x = sum([(n-i)**3 for i in range(n)])
        if x == m:
            return n
        else:
            continue
    return -1

print(find_nb(135440716410000))

答案1

得分: -1

def findNb(m):
  n = 0
  while m > 0:
      n += 1
      m -= n**3
  return n if m == 0 else -1
英文:

You can use this by python:

def findNb(m):
  n = 0
  while m > 0:
      n += 1
      m -= n**3
  return n if m == 0 else -1

huangapple
  • 本文由 发表于 2023年2月16日 03:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定