6
$\begingroup$

The line Table[Prime[n],{n,1000}] produces the list of first 1000 primes. Given this list how can the values be grouped by the values of their tens digit? i.e. how to have the primes in 10s together. and then primes in 20s together and so on up to primes in 7900s?

$\endgroup$
8
$\begingroup$
m = 100;
table = Table[Prime[n], {n, m}];

GroupBy[table, IntegerDigits[#, 10, 6][[-2]] &]
<|0 -> {2, 3, 5, 7, 101, 103, 107, 109, 307, 401, 409, 503, 509}, 
 1 -> {11, 13, 17, 19, 113, 211, 311, 313, 317, 419}, 
 2 -> {23, 29, 127, 223, 227, 229, 421, 521, 523}, 
 3 -> {31, 37, 131, 137, 139, 233, 239, 331, 337, 431, 433, 439}, 
 4 -> {41, 43, 47, 149, 241, 347, 349, 443, 449, 541}, 
 5 -> {53, 59, 151, 157, 251, 257, 353, 359, 457}, 
 6 -> {61, 67, 163, 167, 263, 269, 367, 461, 463, 467}, 
 7 -> {71, 73, 79, 173, 179, 271, 277, 373, 379, 479}, 
 8 -> {83, 89, 181, 281, 283, 383, 389, 487}, 
 9 -> {97, 191, 193, 197, 199, 293, 397, 491, 499}|>
m = 1000;
table = Table[Prime[n], {n, m}];
GroupBy[table, IntegerDigits[#, 10, 6][[-2]] &] // Short[#, 10] &
<|0->{2, 3, 5, 7, 101, 103, 107, 109, 307, 401, 409, 503, 509, 601,607, 
701, 709, 809, 907, 1009, 1103, 1109, 1201, 1301, 1303,1307, 1409,1601,1607, 
1609, 1709, 1801,1901,1907,2003,2203,2207,2309,2503, 2609,2707, 2801, 2803, 
2903, 2909,3001,3109,3203,3209,3301,3307,3407,3607,3701, 3709,3803, 3907, 
4001, 4003,4007,4201,4409,4507,4603,4703,4801,4903,4909,5003,5009, 5101, 
5107, 5209,5303,5309,5407,5501,5503,5507,5701,5801,5807,5903,6007,6101, 6203, 
6301, 6607,6701,6703,6709,6803,6907,7001,7103,7109,7207,7307,7309, 7507, 
7603, 7607,7703,7901,7907},
<<8>>,
9 -> {97,191,193,197,199,293,397,491,499,593,599,691,797,991, 
997,1091,1093,1097,1193,1291,1297,1399,1493,1499,1597,1693,1697, 
1699,1993,1997,1999,2099,2293,2297,2393,<<28>>, 4691, 4793,4799,4993,4999, 
5099, 5197,5297,5393,5399,5591,5693,5791,5897,6091,6197,6199, 6299, 6397, 
6491, 6599,6691,6791,6793,6899,6991,6997,7193,7297,7393, 7499,7591, 7691, 
7699, 7793}|>

Update: Using Mod[Quotient[#, 10], 10] & instead of IntegerDigits[...] as suggested by J.M. in comments, is much faster for large m:

m = 1000000;
table = Table[Prime[n], {n, m}];
assoc1 = GroupBy[table, IntegerDigits[#, 10, 6][[-2]] &]; // RepeatedTiming // First
 0.196
assoc2 = GroupBy[table, Mod[Quotient[#, 10], 10] &]; // RepeatedTiming // First
 0.12
assoc1 == assoc2
 True
| improve this answer | |
$\endgroup$
  • 4
    $\begingroup$ This should be a little bit faster: GroupBy[Table[Prime[n], {n, 100}], Mod[Quotient[#, 10], 10] &]. $\endgroup$ – J. M.'s technical difficulties Jun 5 at 5:55
  • $\begingroup$ Thank you @J.M.; great point. Updated with your suggestion. $\endgroup$ – kglr Jun 5 at 6:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.