algorithm - Sum of all numbers in a given range with some constraints -


my objective find sum of numbers 4 666554 consists of 4,5,6 , satisfying below constraints.

constraints on number of times digit appears

  1. number of time 4 appears in number <= 1
  2. number of time 5 appears in number <= 2
  3. number of time 6 appears in number <= 3

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

simple method run loop , add numbers made of 4,5 , 6 satisfying above constraints.

long long sum = 0; for(int i=4;i <=666554;i++){    /*check if number contains 4,5 , 6 , constraints not violated      if condition true add number sum*/ } 

but seems inefficient. checking number made of 4,5 , 6 , number not violating constraints take time. there way increase efficiency. have tried lot no new approach have found.please help.

you should examine consisting of digits 4,5 , 6, of there few hundred.

that's not difficult: in loop, don't increase 1.

if % 10 < 6 increase 1.

otherwise, subtract 2 (for example 646 turns 644, 6 turns 4); if < 10 add 40 , you're done, , if % 100 < 60 increase 10 , done.

otherwise, subtract 20 (for example 5466 turned 5464 5444); if < 100 add 400 , you're done, , if % 1000 < 600 increase 100 , done.

and on , on. way, don't examine 600,000 numbers 800.

an better approach not finding numbers @ all. let's @ 6 digit numbers. digit 4 can in 6 positions. digit 5 can in (5 * 4) / 2 = 10 positions, digit 6 must in remaining positions. there 60 numbers, containing 60 digits 4, 120 digits 5, 180 digits 6. each digit turns in positions, sum 10 * 444444 + 20 * 555555 + 30 * 666666. similar calculation 1 .. 5 digits.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -