Neighbour primes: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: added an alias.)
(Added C# version, showing totals for some other offsets.)
Line 51: Line 51:
Found 20 neighbour primes up to 500
Found 20 neighbour primes up to 500
</pre>
</pre>

=={{header|C#|CSharp}}==
How about some other offsets besides <code>+ 2</code> ?
<lang fsharp>using System; using System.Collections.Generic;
using System.Linq; using static System.Console; using System.Collections;

class Program {
static void Main(string[] args) {
WriteLine ("Multiply two consecutive prime numbers, add an even number," +
" see if the result is a prime number (up to a limit).");
int c, lim = 500; var pr = PG.Primes(lim * lim).ToList();
pr = pr.TakeWhile(x => x < lim).ToList();
var Lst = new[]{ Tuple.Create(2, 2), Tuple.Create(-20, 20) };
foreach (var pair in Lst) {
bool sho = pair.Item1 == pair.Item2;
for (int ofs = pair.Item1; ofs <= pair.Item2; ofs += ofs == -2 ? 4 : 2) {
c = 0; string s = ofs.ToString("+0;-#").Insert(1, " ");
for (int i = 0, j = 1, k; j < pr.Count; i = j++)
if (PG.isPr(k = pr[i] * pr[j] + ofs))
if (sho) WriteLine (" {0,3} * {1,3} {2} = {3,-6}",
pr[i], pr[j], s, k, c++);
else c++;
WriteLine("{0,2} found under {1} for \" {2} \"", c, lim, s);
} WriteLine (); } } }

class PG { static bool[] flags; public static bool isPr(int x) {
if (x < 2) return false; return !flags[x]; }
public static IEnumerable<int> Primes(int lim) {
flags = new bool[lim + 1]; int j = 3;
for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8)
if (!flags[j]) { yield return j;
for (int k = sq, i=j<<1; k<=lim; k += i) flags[k] = true; }
for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }</lang>
{{out}}
<pre>Multiply two consecutive prime numbers, add an even number, see if the result is a prime number (up to a limit).
3 * 5 + 2 = 17
5 * 7 + 2 = 37
7 * 11 + 2 = 79
13 * 17 + 2 = 223
19 * 23 + 2 = 439
67 * 71 + 2 = 4759
149 * 151 + 2 = 22501
179 * 181 + 2 = 32401
229 * 233 + 2 = 53359
239 * 241 + 2 = 57601
241 * 251 + 2 = 60493
269 * 271 + 2 = 72901
277 * 281 + 2 = 77839
307 * 311 + 2 = 95479
313 * 317 + 2 = 99223
397 * 401 + 2 = 159199
401 * 409 + 2 = 164011
419 * 421 + 2 = 176401
439 * 443 + 2 = 194479
487 * 491 + 2 = 239119
20 found under 500 for " + 2 "

5 found under 500 for " - 20 "
26 found under 500 for " - 18 "
22 found under 500 for " - 16 "
10 found under 500 for " - 14 "
22 found under 500 for " - 12 "
21 found under 500 for " - 10 "
13 found under 500 for " - 8 "
32 found under 500 for " - 6 "
20 found under 500 for " - 4 "
5 found under 500 for " - 2 "
20 found under 500 for " + 2 "
9 found under 500 for " + 4 "
36 found under 500 for " + 6 "
18 found under 500 for " + 8 "
11 found under 500 for " + 10 "
27 found under 500 for " + 12 "
20 found under 500 for " + 14 "
8 found under 500 for " + 16 "
17 found under 500 for " + 18 "
25 found under 500 for " + 20 "</pre>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==