library(gmp)
count2 = function(s, n) {
if (nchar(s) == 1) {
return(as.bigz(as.integer(s) >= n))
} else {
left = as.integer(substring(s, 1, 1))
s = substring(s, 2, nchar(s))
result = left*nchar(s)*as.bigz(10)^(nchar(s)-1) -
(n == 0)*as.bigz(10)^(nchar(s))
if (left == n) {
result = result + as.bigz(sub("^0+([0-9]+)", "\\1", s))+1
} else if (left > n) {
result = result + as.bigz(10)^nchar(s)
}
return(result + Recall(s, n))
}
}
# 整数 a から 整数 b までに数字 n は何個あるか
# a, b は文字列,n は数値で与える
count = function(a, b, n) {
n.b = count2(b, n)
n.a = if (as.bigz(a) == 0) as.bigz(0) else count2(as.character(as.bigz(a)-1), n)
n.b-n.a
}
> print(count("14", "72", 1), initLine=FALSE) # ans = 12 , ans0 = 2 FALSE
[1] 12
> print(count("193", "201", 9), initLine=FALSE) # ans = 8 , ans0 = 18 FALSE
[1] 8
> print(count("144", "218", 9), initLine=FALSE) # ans = 17 , ans0 = 27 FALSE
[1] 17
> print(count("558", "960", 9), initLine=FALSE) # ans = 142 , ans0 = 141 FALSE
[1] 142
> print(count("6211", "19382", 9), initLine=FALSE) # ans = 5310 , ans0 = 5300 FALSE
[1] 5310
> print(count("10416", "18923", 5), initLine=FALSE) # ans = 3600 , ans0 = 3601 FALSE
[1] 3600
> print(count("288292", "935605", 0), initLine=FALSE) # ans = 329167 , ans0 = 329168 FALSE
[1] 329167
> print(count("633636", "635889", 2), initLine=FALSE) # ans = 645 , ans0 = 655 FALSE
[1] 645
> print(count("151642695", "184774424", 0), initLine=FALSE) # ans = 22862553 , ans0 = 22862552 FALSE
[1] 22862553
> print(count("52586824", "348090208", 0), initLine=FALSE) # ans = 236341495 , ans0 = 236341485 FALSE
[1] 236341495
> print(count("135279539884", "865804912485", 1), initLine=FALSE) # ans = 865138642422 , ans0 = 865138642421 FALSE
[1] 865138642422
> print(count("1761231736987", "22345608831150", 0), initLine=FALSE) # ans = 26743902079488 , ans0 = 26743902079487 FALSE
[1] 26743902079488
> print(count("6535079026811", "20167019383277", 9), initLine=FALSE) # ans = 18391758529453 , ans0 = 18391758529454 FALSE
[1] 18391758529453