首页 > 解决方案 > 求平方的另一种方法

问题描述

几年前我提出了这种技术。它似乎工作正常。

输入:一个数字

输出:它的正方形

x=int(input("Enter the number whose square you wish to find out: "))  #decimal input invalid
last_digit=x%10
#We will use formula Sn= (n/2)*(2a+ (n-1)d) of AP
a=100 + last_digit*20 #100,20 are fixed values
d=200 #200 is a fixed value
n=(x-last_digit)/10

final_answer=(n/2)*(2*a + (n-1)*d) + last_digit**2 #These calculations are easier than x*x for a vvlarge x
#normal multiplication is d*d digits, but this is d*(d-1) or d*(d-2) digits

print("My answer:     " ,format(final_answer,'f'))
print("Actual answer: ", x**2)

我已经写了评论来说明我在每一步都在做什么

-> 这是如何工作的?喜欢认真吗?我通过观察一些模式并对其进行概括得到了这一点 -> 此代码仅适用于 3 位数字,但它适用于所有数字。如何?

通过扩展/替换,我的“推导”如下:-

注意:L=last_digit

n = (xL)/10 #和n=x//10一样

a = 100 + 20L

d = 200

我们的最终答案是:-

=> (n/2) * (2a + (n-1)d ) + L^2

替换变量的值,

=> [(xL)/20] * [200 + 40L + [(xL)/10]*200 - 200] + L^2

取 [(xL)/20] 中的 20 并将其带到 * 符号的 RHS,

=> (xL) * [10 + 2L + x - L -10] + L^2

=> (xL)*(x+L) + L^2

=> x^2 - L^2 + L^2

=> x^2

标签: pythonpython-3.xalgorithm

解决方案


您的算法无法处理大量数字。我只对整数进行了尝试,这是一些结果不同的整数列表-

94906267 94906269 94906271 等等……

这里要注意的一件有趣的事情是所有造成问题的数字都是奇数。


推荐阅读