如何有效地找到一个数字对,其中一个平方等于另一个的立方体?
我需要找到对(i,j)
和数字n
的对数,以便满足以下条件: 1< = i< = j< = n以及i * i * i = j * j。
例如,对于n = 50
,对数为3 IE,(1,1)
,(4,8)
,(9,27)
。
我尝试了以下功能代码,但要花费太多时间,例如n = 10000
或更多:
def compute_pairs(N):
pair = []
for i in range (1, N):
for j in range (i, N):
print( 'j =', j)
if i*i*i == j*j:
new_pair = (i,j)
pair.append(new_pair)
print(pair)
return len(pair)
I need to find the pairs (i,j)
and number of pairs for a number N
such that the below conditions are satisfied:
1 <= i <= j <= N and also i * i * i = j * j.
For example, for N = 50
, number of pairs is 3 i.e., (1,1)
, (4,8)
, (9,27)
.
I tried the below function code but it takes too much time for a large number like N = 10000
or more:
def compute_pairs(N):
pair = []
for i in range (1, N):
for j in range (i, N):
print( 'j =', j)
if i*i*i == j*j:
new_pair = (i,j)
pair.append(new_pair)
print(pair)
return len(pair)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
令
k
是某些整数的平方根i
满足i*i*i*i == j*j*j*j
,其中j 也是整数。由于
k
是整数的平方根,因此k*k
是整数。从等式,我们可以解决j
等于k*k*k*k
,因此这也是一个整数。由于
k*k*k
是一个整数,k*k*k
是一个整数,因此通过将这两个划分为k
是合理的。但是k
是整数的平方根,因此它必须是整数或不合理的。由于它是理性的,因此必须是一个整数。由于
k
是整数,因此所有解决方案都是(k*k,k*k*k)
for Integerk
。由于我们将通过k&gt; = 1
迭代,因此我们知道k*k&lt; = k*k*k*k
,即i&lt; = j ,因此我们不必担心。当
k*k*k
到达n
时,我们只需要停止迭代。即使对于100000的
n
,这也几乎即时运行,无需C级优化。Let
k
be the square root of some integeri
satisfyingi*i*i == j*j
, wherej
is also an integer. Sincek
is the square root of an integer,k*k
is integer. From the equation, we can solve thatj
is equal tok*k*k
, so that is also an integer.Since
k*k*k
is an integer andk*k
is an integer, it follows by dividing these two thatk
is rational. Butk
is the square root of an integer, so it must be either an integer or irrational. Since it is rational, it must be an integer.Since
k
is an integer, all the solutions are simply(k*k, k*k*k)
for integerk
. Since we will iterate overk>=1
, we know thatk*k <= k*k*k
, i.e.i <= j
, so we don't have to worry about that. We just have to stop iterating whenk*k*k
reachesN
.This runs almost instantaneously even for
N
of 100000, no C-level optimization needed.考虑一下问题。您需要
i
立方体与j
平方相同吗?我们知道对
(0,0)
,(1,1)
,(4,8)
和(9) ,27)
满足此条件。0
, 1 ,4
和9
都有什么共同点?它们
0
,1
,2
和3
平方。那么
0
, 1 ,8
和27
都有什么共同点?它们是相同的数字。
一旦意识到模式,答案就可以在很短的时间内计算出来。
Think about the problem. You need
i
cubed to be the same asj
squared?We know that pairs like
(0, 0)
,(1, 1)
,(4, 8)
, and(9, 27)
satisfy this condition.What do
0
,1
,4
, and9
all have in common?They're
0
,1
,2
, and3
squared.What then do
0
,1
,8
, and27
all have in common?They're the same numbers cubed.
Once you realize the pattern, the answer can be calculated in extremely short time.