python - 求平方的另一种方法
问题描述
几年前我提出了这种技术。它似乎工作正常。
输入:一个数字
输出:它的正方形
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
解决方案
您的算法无法处理大量数字。我只对整数进行了尝试,这是一些结果不同的整数列表-
94906267 94906269 94906271 等等……
这里要注意的一件有趣的事情是所有造成问题的数字都是奇数。
推荐阅读
- react-native - 反应原生版本 0.59.6 苹果按钮登录不可见反应
- c++ - 我想修复在尝试编译 xenGT 时发生的错误
- django - 从图形(neo4j)数据库中检索与 graphene-django 和 graphql 的关系属性
- python - 有人对如何在 OpenCV 中解决这个问题有建议吗?
- azure - AZure Logic Apps SFTP 连接器回复 504 错误网关
- ruby-on-rails - 将音频播放器添加到活动管理面板
- php - 如何在数组的超链接中包含文件名?
- reactjs - 如何使具有多个对象的对象成为状态数组?
- c# - The given key was not present in the dictionary exception
- java - Bottomnavigationbar 无法将可检查设置为 false,但 true 可以正常工作