在给定的范围内写有特定位的所有数字的总和 [英] Sum of all numbers written with particular digits in a given range

查看:119
本文介绍了在给定的范围内写有特定位的所有数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是要找到从4所有数字之和为666554其中包括4,5,6只。

My objective is to find the sum of all numbers from 4 to 666554 which consists of 4,5,6 only.

SUM = 4+5+6+44+45+46+54+55+56+64+65+66+.....................+666554.

简单的方法是运行一个循环,并添加制成的4,5和6只的数量。

Simple method is to run a loop and add the numbers made of 4,5 and 6 only.

long long sum = 0;
for(int i=4;i <=666554;i++){
   /*check if number contains only 4,5 and 6.
     if condition is true then add the number to the sum*/
}

不过,这似乎是低效的。检查该号码是由4,5和6需要时间。有没有什么办法来提高效率。我已经尝试了很多,但没有新的方法,我已经found.Please帮助。

But it seems to be inefficient. Checking that the number is made up of 4,5 and 6 will take time. Is there any way to increase the efficiency. I have tried a lot but no new approach i have found.Please help.

推荐答案

对于1位号码,请注意

4 + 5 + 6 == 5 * 3

有关2位号码:

(44 + 45 + 46) + (54 + 55 + 56) + (64 + 65 + 66)
== 45 * 3 + 55 * 3 + 65 * 3
== 55 * 9

等等。

在一般情况下, N -digits号,还有3 N 其中包括 4 5 6 只,它们的平均价值是完全 5 .. 0.5 N 位)。使用code,它们的总和('5'* N).to_i * 3 ** N (红宝石),或 INT (5* N)* 3 ** N (蟒蛇)。

In general, for n-digits numbers, there are 3n of them consist of 4,5,6 only, their average value is exactly 5...5(n digits). Using code, the sum of them is ('5' * n).to_i * 3 ** n (Ruby), or int('5' * n) * 3 ** n (Python).

您计算高达6位数字号码,然后减去的总和 666555 666666

You calculate up to 6-digits numbers, then subtract the sum of 666555 to 666666.

PS:对于小的数字,例如 666554 ,使用模式匹配的速度不够快。 (例如

P.S: for small numbers like 666554, using pattern matching is fast enough. (example)

这篇关于在给定的范围内写有特定位的所有数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆