# select from a list based on digits

I wish to know how do I count the number of occurrences of numbers that end in digits d. e.g. Say I create a list of Divisors of 12! I now want to count those divisors that end in 12. Like 12 & 112 would qualify but 120 would not.

Thanks.

-

In most cases you can use Mod:

d = Divisors[12!];
last2 = Mod[d, 10^2];

Count[last2, 12]
Pick[d, last2, 12]

11

{12, 112, 512, 1512, 2112, 6912, 19712, 28512, 64512, 266112, 870912}


If the sequence you are looking for starts with zero, e.g. you are searching for 01 and you want 1001 to match but 1 not to match, you could use:

Cases[Range[1500], x_ /; MatchQ[IntegerDigits @ x, {___, 0, 1}]]

{101, 201, 301, 401, 501, 601, 701, 801, 901, 1001, 1101, 1201, 1301, 1401}


This code is not vectorized so it is unlikely to be very fast but it does conserve memory; if speed is important let me know.

-
Nice math!. I did not think/know that mod 12 would pick all values that end up with 12 and nothing else. But I guess since these values are divisors, then it should follow. –  Nasser Jun 3 at 2:11
@Nasser Thanks, but that's not actually what I wrote. :^) I'm just using mod 100 to pull the last two digits, then using standard pattern matching to check the result. –  Mr.Wizard Jun 3 at 2:19
You are right, I saw Mod there with 12 next to it. Need new glasses. Either way, smart method –  Nasser Jun 3 at 2:52

one way (if you do not want the list itself, just the count *)

lst = IntegerDigits[Divisors[12!]];
k = 0;
If[ Length[#] > 1 && FromDigits[Take[#, -2]] == 12, k++] & /@ lst;
k
(* 11 *)


And if you want the list also:

lst = IntegerDigits[Divisors[12!]];
lst2 = Cases[lst, x_ /; Length[x] > 1 && FromDigits[Take[x, -2]] == 12];
Length[lst2]
(* 11 *)


Or using Select

lst = IntegerDigits[Divisors[12!]];
Length@Select[lst, (Length[#] > 1 && FromDigits[Take[#, -2]] == 12) &];
(* 11 *)

-
Also Count[lst, x_ /; Last@IntegerDigits[x] == 2] as a modification of the second method to just count. –  acl Jun 2 at 15:25
@acl - very nice ! didn't know that one can plug a condition into "Count". –  eldo Jun 2 at 17:54
note he wanted to match the last two digits. –  george2079 Jun 2 at 20:21
@george2079 opps, ok, easy to fix, thanks. will do that now. –  Nasser Jun 2 at 20:34
@eldo patterns can include conditions wherever they're allowed –  acl Jun 3 at 1:14