Algorithm for 'good' number

后端 未结 3 1688
梦毁少年i
梦毁少年i 2021-01-29 07:02

A give number x is \'good\' if the sum of any two consecutive digit of the number x are between k and 2k. I need to find an algorithm that for a given number k and a given numbe

3条回答
  •  日久生厌
    2021-01-29 07:14

    Your algorithm counts how many 2 digit integers are NOT good. Then it returns this value to the power of n - 1. This should get you the number of n digit numbers that are NOT good. If you subtract this value from the total amount of n digit integers, you should get what you want. Or we could avoid doing this by changing the signs:

    for($i=10; $i<100; $i++) {
     if( ($i/10) + ($i%10) > $k && ($i/10) + ($i%10) < 2*$k ) {
      $cnt++;
     }
    }
    $result = pow($cnt, $n-1);
    

    This should get you the number of good n digit integers, but let's see if that's really the case.

    Well, cnt will give the number of good 2 digit integers. So, on the first two positions, we can put any of these cnt:

    0 1 2 3 4 5 ...
    x y
    

    Then, what about positions 1 and 2? Well, position 1 is fixed by the first placement.

    0 1 2 3 4 5 ...
    x y
      y z
    

    So we have to prove that there are cnt possibilities for z, and I don't see why this should be the case, so I would say that the algorithm is wrong. Your algorithm will probably overcount.

提交回复
热议问题