所有数字在给定范围内具有某些约束总和范围内、总和、数字

2023-09-11 22:41:56 作者:要要切客闹抗忙北鼻来抱抱

我的目标是要找到从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 and satisfying below constraints.

上的次数限制将出现一个数字

Constraints on number of times a digit appears

时间4号出现的数量和LT = 1 时间5号出现的数量和LT = 2

时间6出现在数量和其中数= 3 Number of time 4 appears in the number <= 1 Number of time 5 appears in the number <= 2

Number of time 6 appears in the number <= 3

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

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

简单的方法是运行一个循环,并添加制成的4,5和6被满足上述约束的数字。

Simple method is to run a loop and add the numbers made of 4,5 and 6 which is satisfying above constraints.

long long sum = 0;
for(int i=4;i <=666554;i++){
   /*check if number contains only 4,5 and 6 and constraints are not violated
     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 and number is not violating the constraints 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.

推荐答案

您应该只研究那些由数字4,5和6,其中有只有几百个。

You should only examine those consisting of the digits 4,5 and 6, of which there are only a few hundred.

这不是太困难:在你的循环,不只是增加我1。

That's not too difficult: In your loop, don't just increase i by 1.

如果我%10&LT; 6,那么你只是增加我1。

If i % 10 < 6 then you just increase i by 1.

否则,减去2(例如646变成644,6变成4);如果我&LT; 10再加入40就大功告成了,如果我%,100℃, 60则只是增加我10和你做。

Otherwise, subtract 2 (for example 646 turns into 644, 6 turns into 4); if i < 10 then add 40 and you're done, and if i % 100 < 60 then just increase i by 10 and you are done.

否则,减去20(例如5466变成了5464,然后5444);如果我&LT; 100再加入400就大功告成了,如果我%,1000℃; 600则只是增加我100,和你做。

Otherwise, subtract 20 (for example 5466 turned into 5464 then 5444); if i < 100 then add 400 and you're done, and if i % 1000 < 600 then just increase i by 100 and you are done.

等等等等。这样一来,你不检查60万的数字,但只有约800

And so on and so on. That way, you don't examine about 600,000 numbers but only about 800.

这是更好的方法没有找到的数字都没有。让我们来看看六位数字。数字4可以在六个位置。数字5可以是在(5 * 4)/ 2 = 10的位置,数字6必须在剩余位置。因此只有60个数字,含60个数字4,120位5,180位6.每个数字变成了在所有位置,因此,总和为10 * 444444 + 20 * 555555 + 30 * 666666你做类似的计算1 .. 5位。

An even better approach is not finding the numbers at all. Let's look at six digit numbers. The digit 4 can be in six positions. The digit 5 can be in (5 * 4) / 2 = 10 positions, the digit 6 must be in the remaining positions. So there are only 60 numbers, containing 60 digits 4, 120 digits 5, 180 digits 6. Each digit turns up in all positions, so the sum is 10 * 444444 + 20 * 555555 + 30 * 666666. You do a similar calculation for 1 .. 5 digits.