Strong and weak primes: Difference between revisions
m
→{{header|EasyLang}}
No edit summary |
|||
(34 intermediate revisions by 19 users not shown) | |||
Line 7:
:::::* '''prime(4)''' is '''7'''
::* A ''' strong prime''' is when <big>'''prime(''p'')'''</big> is <big>'''>''' '''[prime(''p''-1) + prime(''p''+1)] ÷ 2</big>'''
::* A ''' weak prime''' is when <big>'''prime(''p'')'''</big> is <big>'''<''' '''[prime(''p''-1) + prime(''p''+1)] ÷ 2</big>'''
Line 27:
;Related Task:
::* [[Safe primes
;Also see:
::* The OEIS article
::* The OEIS article
<br><br>
=={{header|11l}}==
<syntaxhighlight lang="11l">F primes_upto(limit)
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
R enumerate(is_prime).filter((i, prime) -> prime).map((i, prime) -> i)
V p = primes_upto(10'000'000)
[Int] s, w, b
L(i) 1 .< p.len - 1
I p[i] > (p[i - 1] + p[i + 1]) * 0.5
s [+]= p[i]
E I p[i] < (p[i - 1] + p[i + 1]) * 0.5
w [+]= p[i]
E
b [+]= p[i]
print(‘The first 36 strong primes: ’s[0.<36])
print(‘The count of the strong primes below 1,000,000: ’sum(s.filter(p -> p < 1'000'000).map(p -> 1)))
print(‘The count of the strong primes below 10,000,000: ’s.len)
print("\nThe first 37 weak primes: "w[0.<37])
print(‘The count of the weak primes below 1,000,000: ’sum(w.filter(p -> p < 1'000'000).map(p -> 1)))
print(‘The count of the weak primes below 10,000,000: ’w.len)
print("\n\nThe first 10 balanced primes: "b[0.<10])
print(‘The count of balanced primes below 1,000,000: ’sum(b.filter(p -> p < 1'000'000).map(p -> 1)))
print(‘The count of balanced primes below 10,000,000: ’b.len)
print("\nTOTAL primes below 1,000,000: "sum(p.filter(pr -> pr < 1'000'000).map(pr -> 1)))
print(‘TOTAL primes below 10,000,000: ’p.len)</syntaxhighlight>
{{out}}
<pre>
The first 36 strong primes: [11, 17, 29, 37, 41, 59, 67, 71, 79, 97, 101, 107, 127, 137, 149, 163, 179, 191, 197, 223, 227, 239, 251, 269, 277, 281, 307, 311, 331, 347, 367, 379, 397, 419, 431, 439]
The count of the strong primes below 1,000,000: 37723
The count of the strong primes below 10,000,000: 320991
The first 37 weak primes: [3, 7, 13, 19, 23, 31, 43, 47, 61, 73, 83, 89, 103, 109, 113, 131, 139, 151, 167, 181, 193, 199, 229, 233, 241, 271, 283, 293, 313, 317, 337, 349, 353, 359, 383, 389, 401]
The count of the weak primes below 1,000,000: 37780
The count of the weak primes below 10,000,000: 321749
The first 10 balanced primes: [5, 53, 157, 173, 211, 257, 263, 373, 563, 593]
The count of balanced primes below 1,000,000: 2994
The count of balanced primes below 10,000,000: 21837
TOTAL primes below 1,000,000: 78498
TOTAL primes below 10,000,000: 664579
</pre>
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<
PR heap=128M PR # set heap memory size for Algol 68G #
# returns a string representation of n with commas #
Line 128 ⟶ 178:
print( ( newline ) );
print( ( " weak primes below 1,000,000: ", commatise( weak1 ), newline ) );
print( ( " weak primes below 10,000,000: ", commatise( weak10 ), newline ) )</
{{out}}
<pre>
Line 139 ⟶ 189:
weak primes below 1,000,000: 37,780
weak primes below 10,000,000: 321,750
</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f STRONG_AND_WEAK_PRIMES.AWK
BEGIN {
for (i=1; i<1E7; i++) {
if (is_prime(i)) {
arr[++n] = i
}
}
# strong:
stop1 = 36 ; stop2 = 1E6 ; stop3 = 1E7
count1 = count2 = count3 = 0
printf("The first %d strong primes:",stop1)
for (i=2; count1<stop1; i++) {
if (arr[i] > (arr[i-1] + arr[i+1]) / 2) {
count1++
printf(" %d",arr[i])
}
}
printf("\n")
for (i=2; i<stop3; i++) {
if (arr[i] > (arr[i-1] + arr[i+1]) / 2) {
count3++
if (arr[i] < stop2) {
count2++
}
}
}
printf("Number below %d: %d\n",stop2,count2)
printf("Number below %d: %d\n",stop3,count3)
# weak:
stop1 = 37 ; stop2 = 1E6 ; stop3 = 1E7
count1 = count2 = count3 = 0
printf("The first %d weak primes:",stop1)
for (i=2; count1<stop1; i++) {
if (arr[i] < (arr[i-1] + arr[i+1]) / 2) {
count1++
printf(" %d",arr[i])
}
}
printf("\n")
for (i=2; i<stop3; i++) {
if (arr[i] < (arr[i-1] + arr[i+1]) / 2) {
count3++
if (arr[i] < stop2) {
count2++
}
}
}
printf("Number below %d: %d\n",stop2,count2)
printf("Number below %d: %d\n",stop3,count3)
exit(0)
}
function is_prime(n, d) {
d = 5
if (n < 2) { return(0) }
if (n % 2 == 0) { return(n == 2) }
if (n % 3 == 0) { return(n == 3) }
while (d*d <= n) {
if (n % d == 0) { return(0) }
d += 2
if (n % d == 0) { return(0) }
d += 4
}
return(1)
}
</syntaxhighlight>
{{out}}
<pre>
The first 36 strong primes: 11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
Number below 1000000: 37723
Number below 10000000: 320992
The first 37 weak primes: 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
Number below 1000000: 37781
Number below 10000000: 321750
</pre>
=={{header|C}}==
{{trans|D}}
<
#include <stdint.h>
#include <stdio.h>
Line 264 ⟶ 390:
free(primePtr);
return EXIT_SUCCESS;
}</
{{out}}
<pre>First 36 strong primes: 11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
Line 276 ⟶ 402:
=={{header|C sharp}}==
{{works with|C sharp|7}}
<
using static System.Linq.Enumerable;
using System;
Line 294 ⟶ 420:
}
}</
{{out}}
<pre>
Line 305 ⟶ 431:
=={{header|C++}}==
<
#include <
#include <iterator>
#include <locale>
#include <
#include "
const int limit1 = 1000000;
const int limit2 = 10000000;
class prime_info {
public:
explicit prime_info(int max) : max_print(max) {}
void add_prime(int prime);
void print(std::ostream& os, const char* name) const;
private:
int max_print;
int count1 = 0;
int count2 = 0;
std::vector<int> primes;
};
void prime_info::add_prime(int prime) {
++count2;
if (prime < limit1)
++count1;
if (count2 <= max_print)
primes.push_back(prime);
}
void prime_info::print(std::ostream& os, const char* name) const {
os << "First " << max_print << " " << name << " primes: ";
std::copy(primes.begin(), primes.end(), std::ostream_iterator<int>(os, " "));
os << '\n';
os << "Number of " << name << " primes below " << limit1 << ": " << count1 << '\n';
os << "Number of " << name << " primes below " << limit2 << ": " << count2 << '\n';
}
int main() {
prime_sieve sieve(limit2 + 100);
// write numbers with groups of digits separated according to the system default locale
std::cout.imbue(std::locale(""));
// count and print strong/weak prime numbers
prime_info strong_primes(36);
prime_info weak_primes(37);
int p1 = 2, p2 = 3;
for (int p3 = 5; p2 < limit2; ++p3) {
if (!sieve.is_prime(p3))
continue;
int diff = p1 + p3 - 2 * p2;
p1 = p2;
p2 = p3;
}
strong_primes.print(std::cout, "strong");
weak_primes.print(std::cout, "weak");
return 0;
}</
Contents of
<
#define
#include <algorithm>
#include <vector>
/**
* A simple implementation of the Sieve of Eratosthenes.
* See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes.
*/
class prime_sieve {
public:
explicit
bool is_prime(size_t) const;
private:
Line 376 ⟶ 514:
};
/**
* Constructs a sieve with the given limit.
*
* @param limit the maximum integer that can be tested for primality
*/
inline
is_prime_.resize(limit/2, true);
for (size_t p = 3; p * p <= limit; p += 2) {
size_t inc = 2 * p;
is_prime_[q/2 - 1] = false;
}
}
}
/**
* Returns true if the given integer is a prime number. The integer
* must be less than or equal to the limit passed to the constructor.
*
* @param n an integer less than or equal to the limit passed to the
* constructor
* @return true if the integer is prime
*/
inline bool prime_sieve::is_prime(size_t n) const {
if (n == 2)
return true;
if (n < 2 || n % 2 == 0)
return false;
return is_prime_.at(n/2 - 1);
}
#endif</syntaxhighlight>
{{out}}
<pre>
First 36 strong primes: 11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
Number of strong primes below 1,000,000: 37,723
Number of strong primes below 10,000,000: 320,991
First 37 weak primes: 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
Number of weak primes below 1,000,000: 37,780
Number of weak primes below 10,000,000: 321,750
Line 408 ⟶ 560:
=={{header|D}}==
<
import std.array;
import std.range;
Line 501 ⟶ 653:
writefln("There are %d weak primes below 1,000,000", weakPrimes.filter!"a<1_000_000".count);
writefln("There are %d weak primes below 10,000,000", weakPrimes.filter!"a<10_000_000".count);
}</
{{out}}
<pre>First 36 strong primes: [11, 17, 29, 37, 41, 59, 67, 71, 79, 97, 101, 107, 127, 137, 149, 163, 179, 191, 197, 223, 227, 239, 251, 269, 277, 281, 307, 311, 331, 347, 367, 379, 397, 419, 431, 439]
Line 509 ⟶ 661:
There are 37780 weak primes below 1,000,000
There are 321750 weak primes below 10,000,000</pre>
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
<syntaxhighlight lang="Delphi">
procedure StrongWeakPrimes(Memo: TMemo);
{Display Strong/Weak prime information}
var I,P: integer;
var Sieve: TPrimeSieve;
var S: string;
var Cnt,Cnt1,Cnt2: integer;
type TPrimeTypes = (ptStrong,ptWeak,ptBalanced);
function GetTypeStr(PrimeType: TPrimeTypes): string;
{Get string describing PrimeType}
begin
case PrimeType of
ptStrong: Result:='Strong';
ptWeak: Result:='Weak';
ptBalanced: Result:='Balanced';
end;
end;
function GetPrimeType(N: integer): TPrimeTypes;
{Return flag indicating type of prime Primes[N] is}
{Strong = Primes(N) > [Primes(N-1) + Primes(N+1)] / 2}
{Weak = Primes(N) < [Primes(N-1) + Primes(N+1)] / 2}
{Balanced = Primes(N) = [Primes(N-1) + Primes(N+1)] / 2}
var P,P1: double;
begin
P:=Sieve.Primes[N];
P1:=(Sieve.Primes[N-1] + Sieve.Primes[N+1]) / 2;
if P>P1 then Result:=ptStrong
else if P<P1 then Result:=ptWeak
else Result:=ptBalanced;
end;
procedure GetPrimeCounts(PT: TPrimeTypes; var Cnt1,Cnt2: integer);
{Get number of primes of type "PT" below 1 million and 10 million}
var I: integer;
begin
Cnt1:=0; Cnt2:=0;
for I:=1 to 1000000-1 do
begin
if GetPrimeType(I)=PT then
begin
if Sieve.Primes[I]>10000000 then break;
Inc(Cnt2);
if Sieve.Primes[I]<1000000 then Inc(Cnt1);
end;
end;
end;
function GetPrimeList(PT: TPrimeTypes; Limit: integer): string;
{Get a list of primes of type PT up to Limit}
var I,Cnt: integer;
begin
Result:='';
Cnt:=0;
for I:=1 to Sieve.PrimeCount-1 do
if GetPrimeType(I)=PT then
begin
Inc(Cnt);
P:=Sieve.Primes[I];
Result:=Result+Format('%5d',[P]);
if Cnt>=Limit then break;
if (Cnt mod 10)=0 then Result:=Result+CRLF;
end;
end;
procedure ShowPrimeTypeData(PT: TPrimeTypes; Limit: Integer);
{Display information about specified PrimeType, listing items up to Limit}
var S,TS: string;
begin
S:=GetPrimeList(PT,Limit);
TS:=GetTypeStr(PT);
Memo.Lines.Add(Format('First %d %s primes are:',[Limit,TS]));
Memo.Lines.Add(S);
GetPrimeCounts(PT,Cnt1,Cnt2);
Memo.Lines.Add(Format('Number %s primes <1,000,000: %8.0n', [TS,Cnt1+0.0]));
Memo.Lines.Add(Format('Number %s primes <10,000,000: %8.0n', [TS,Cnt2+0.0]));
Memo.Lines.Add('');
end;
begin
Sieve:=TPrimeSieve.Create;
try
Sieve.Intialize(200000000);
Memo.Lines.Add('Primes in Sieve : '+IntToStr(Sieve.PrimeCount));
ShowPrimeTypeData(ptStrong,36);
ShowPrimeTypeData(ptWeak,37);
ShowPrimeTypeData(ptBalanced,28);
finally Sieve.Free; end;
end;
</syntaxhighlight>
{{out}}
<pre>
Primes in Sieve : 11078937
First 36 Strong primes are:
11 17 29 37 41 59 67 71 79 97
101 107 127 137 149 163 179 191 197 223
227 239 251 269 277 281 307 311 331 347
367 379 397 419 431 439
Number Strong primes <1,000,000: 37,723
Number Strong primes <10,000,000: 320,991
First 37 Weak primes are:
3 7 13 19 23 31 43 47 61 73
83 89 103 109 113 131 139 151 167 181
193 199 229 233 241 271 283 293 313 317
337 349 353 359 383 389 401
Number Weak primes <1,000,000: 37,780
Number Weak primes <10,000,000: 321,750
First 28 Balanced primes are:
5 53 157 173 211 257 263 373 563 593
607 653 733 947 977 1103 1123 1187 1223 1367
1511 1747 1753 1907 2287 2417 2677 2903
Number Balanced primes <1,000,000: 2,994
Number Balanced primes <10,000,000: 21,837
Elapsed Time: 2.947 Sec.
</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
fastfunc isprim num .
i = 3
while i <= sqrt num
if num mod i = 0
return 0
.
i += 2
.
return 1
.
func nextprim n .
repeat
n += 2
until isprim n = 1
.
return n
.
proc strwkprimes ncnt sgn . .
write "First " & ncnt & ": "
pr2 = 2
pr3 = 3
repeat
pr1 = pr2
pr2 = pr3
until pr2 >= 10000000
pr3 = nextprim pr3
if pr1 < 1000000 and pr2 > 1000000
print ""
print "Count lower 10e6: " & cnt
.
if sgn * pr2 > sgn * (pr1 + pr3) / 2
cnt += 1
if cnt <= ncnt
write pr2 & " "
.
.
.
print "Count lower 10e7: " & cnt
print ""
.
print "Strong primes:"
strwkprimes 36 1
print "Weak primes:"
strwkprimes 37 -1
</syntaxhighlight>
{{out}}
<pre>
Strong primes:
First 36: 11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
Count lower 10e6: 37723
Count lower 10e7: 320991
Weak primes:
First 37: 3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
Count lower 10e6: 37780
Count lower 10e7: 321750
</pre>
=={{header|Factor}}==
<
tools.memory.private ;
IN: rosetta-code.strong-primes
Line 535 ⟶ 883:
First 37 weak primes:\n%[%d, %]
%s weak primes below 1,000,000
%s weak primes below 10,000,000\n" printf</
{{out}}
<pre>
Line 547 ⟶ 895:
37,780 weak primes below 1,000,000
321,750 weak primes below 10,000,000
</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
#include "isprime.bas"
function nextprime( n as uinteger ) as uinteger
'finds the next prime after n, excluding n if it happens to be prime itself
if n = 0 then return 2
if n < 3 then return n + 1
dim as integer q = n + 2
while not isprime(q)
q+=2
wend
return q
end function
function lastprime( n as uinteger ) as uinteger
'finds the last prime before n, excluding n if it happens to be prime itself
if n = 2 then return 0 'zero isn't prime, but it is a good sentinel value :)
if n = 3 then return 2
dim as integer q = n - 2
while not isprime(q)
q-=2
wend
return q
end function
function isstrong( p as integer ) as boolean
if nextprime(p) + lastprime(p) >= 2*p then return false else return true
end function
function isweak( p as integer ) as boolean
if nextprime(p) + lastprime(p) <= 2*p then return false else return true
end function
print "The first 36 strong primes are: "
dim as uinteger c, p=3
while p < 10000000
if isprime(p) andalso isstrong(p) then
c += 1
if c <= 36 then print p;" ";
if c=37 then print
end if
if p = 1000001 then print "There are ";c;" strong primes below one million"
p+=2
wend
print "There are ";c;" strong primes below ten million"
print
print "The first 37 weak primes are: "
p=3 : c=0
while p < 10000000
if isprime(p) andalso isweak(p) then
c += 1
if c <= 37 then print p;" ";
if c=38 then print
end if
if p = 1000001 then print "There are ";c;" weak primes below one million"
p+=2
wend
print "There are ";c;" weak primes below ten million"
print</syntaxhighlight>
{{out}}<pre>
The first 36 strong primes are:
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
There are 37723 strong primes below one million
There are 320991 strong primes below ten million
The first 37 weak primes are:
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
There are 37780 weak primes below one million
There are 321750 weak primes below ten million
</pre>
=={{header|Frink}}==
<
strongPrimes[end=undef] := select[primes[3,end], {|p| p > (previousPrime[p] + nextPrime[p])/2 }]
weakPrimes[end=undef] := select[primes[3,end], {|p| p < (previousPrime[p] + nextPrime[p])/2 }]
Line 561 ⟶ 983:
println["Weak primes below 1,000,000: " + length[weakPrimes[1_000_000]]]
println["Weak primes below 10,000,000: " + length[weakPrimes[10_000_000]]]
</syntaxhighlight>
{{out}}
Line 574 ⟶ 996:
=={{header|Go}}==
<
import "fmt"
Line 659 ⟶ 1,081:
fmt.Println("\nThe number of weak primes below 1,000,000 is", commatize(count))
fmt.Println("\nThe number of weak primes below 10,000,000 is", commatize(len(weak)))
}</
{{out}}
Line 678 ⟶ 1,100:
</pre>
=={{header|Haskell}}==
Uses primes library: http://hackage.haskell.org/package/primes-0.2.1.0/docs/Data-Numbers-Primes.html
<syntaxhighlight lang="haskell">import Text.Printf (printf)
import Data.Numbers.Primes (primes)
xPrimes :: (Real a, Fractional
xPrimes op ps@(p1:p2:p3:xs)
| realToFrac p2 `op` (realToFrac (p1 + p3) / 2) = p2 : xPrimes op (tail ps)
Line 696 ⟶ 1,119:
printf "Weak primes below 10,000,000: %d\n\n" . length . takeWhile (<10000000) $ weakPrimes
where strongPrimes = xPrimes (>) primes
weakPrimes = xPrimes (<) primes</
{{out}}
<pre>
Line 739 ⟶ 1,162:
=={{header|Java}}==
<
public class StrongAndWeakPrimes {
Line 844 ⟶ 1,267:
}
</syntaxhighlight>
{{out}}
<pre>
Line 855 ⟶ 1,278:
Number of weak primes below 1,000,000 = 37,780
Number of weak primes below 10,000,000 = 321,750
</pre>
=={{header|jq}}==
{{Works with|jq}}
'''Also works with gojq, the Go implementation of jq'''
The following assumes that `primes` generates a stream of primes less
than or equal to `.`
as defined, for example, at [[Sieve_of_Eratosthenes#jq|Sieve of Eratosthenes]]]].
<syntaxhighlight lang=jq>
def count(s): reduce s as $_ (0; .+1);
# Emit {strong, weak} primes up to and including $n
def strong_weak_primes:
. as $n
| primes as $primes
| ("\nCheck: last prime generated: \($primes[-1])" | debug) as $debug
| reduce range(1; $primes|length-1) as $p ({};
(($primes[$p-1] + $primes[$p+1]) / 2) as $x
| if $primes[$p] > $x
then .strong += [$primes[$p]]
elif $primes[$p] < $x
then .weak += [$primes[$p]]
else .
end );
(1e7 + 19)
| strong_weak_primes as {$strong, $weak}
| "The first 36 strong primes are:",
$strong[:36],
"\nThe count of the strong primes below 1e6: \(count($strong[]|select(. < 1e6 )))",
"\nThe count of the strong primes below 1e7: \(count($strong[]|select(. < 1e7 )))",
"\nThe first 37 weak primes are:",
$weak[:37],
"\nThe count of the weak primes below 1e6: \(count($weak[]|select(. < 1e6 )))",
"\nThe count of the weak primes below 1e7: \(count($weak[]|select(. < 1e7 )))"
</syntaxhighlight>
{{output}}
<pre>
The first 36 strong primes are:
[11,17,29,37,41,59,67,71,79,97,101,107,127,137,149,163,179,191,197,223,227,239,251,269,277,281,307,311,331,347,367,379,397,419,431,439]
The count of the strong primes below 1e6: 37723
The count of the strong primes below 1e7: 320991
The first 37 weak primes are:
[3,7,13,19,23,31,43,47,61,73,83,89,103,109,113,131,139,151,167,181,193,199,229,233,241,271,283,293,313,317,337,349,353,359,383,389,401]
The count of the weak primes below 1e6: 37780
The count of the weak primes below 1e7: 321750
</pre>
=={{header|Julia}}==
<
function parseprimelist()
Line 890 ⟶ 1,367:
parseprimelist()
</
The first 36 strong primes are: [11, 17, 29, 37, 41, 59, 67, 71, 79, 97, 101, 107, 127, 137, 149, 163, 179, 191, 197, 223, 227, 239, 251, 269, 277, 281, 307, 311, 331, 347, 367, 379, 397, 419, 431, 439]
There are 37,723 stromg primes less than 1 million.
Line 904 ⟶ 1,381:
=={{header|Kotlin}}==
{{trans|Java}}
<
private val primes = BooleanArray(MAX)
Line 1,006 ⟶ 1,483:
}
}
}</
{{out}}
<pre>First 36 strong primes:
Line 1,016 ⟶ 1,493:
Number of weak primes below 1,000,000 = 37,780
Number of weak primes below 10,000,000 = 321,750</pre>
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
# Strong and weak primes
# # Find and display (on one line) the first 36 strong primes.
# # Find and display the count of the strong primes below 1,000,000.
# # Find and display the count of the strong primes below 10,000,000.
# # Find and display (on one line) the first 37 weak primes.
# # Find and display the count of the weak primes below 1,000,000.
# # Find and display the count of the weak primes below 10,000,000.
# # (Optional) display the counts and "below numbers" with commas. ???
# # A strong prime is when prime[p] > (prime[p-1] + prime[p+1]) ÷ 2
# # A weak prime is when prime[p] < (prime[p-1] + prime[p+1]) ÷ 2
# # Balanced prime is when prime[p] = (prime[p-1] + prime[p+1]) ÷ 2
# # Variables:
#
integer NUM_STRONG=36 NUM_WEAK=37 GOAL1=1000000 MAX_INT=10000000
# # Functions:
#
# # Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
typeset _n ; integer _n=$1
typeset _i ; integer _i
(( _n < 2 )) && return 0
for (( _i=2 ; _i*_i<=_n ; _i++ )); do
(( ! ( _n % _i ) )) && return 0
done
return 1
}
# # Function _strength(prime[n], prime[n-1], prime[n+1]) return 1 for strong
#
function _strength {
typeset _pri ; integer _pri=$1 # PRIme number under consideration
typeset _pre ; integer _pre=$2 # PREvious prime number
typeset _nex ; integer _nex=$3 # NEXt prime number
typeset _result ; typeset -F1 _result
(( _result = (_pre + _nex) / 2.0 ))
(( _pri > _result )) && echo STRONG && return 0
(( _pri < _result )) && echo WEAK && return 1
echo BALANCED && return 99
}
#####
# main #
######
integer spcnt=0 wpcnt=0 bpcnt=0 sflg=0 wflg=0 i j k goal1_strong goal1_weak
typeset -C prime # prime[].val prime[].typ
typeset -a prime.val
typeset -a prime.typ
prime.typ[0]='NA' ; prime.typ[1]='NA'
for (( i=2; i<MAX_INT; i++ )); do
_isprime ${i} ; (( ! $? )) && continue
prime.val+=( ${i} )
(( ${#prime.val[*]} <= 2 )) && continue
(( j = ${#prime.val[*]} - 2 )) ; (( k = j - 1 ))
prime.typ+=( $(_strength ${prime.val[${j}]} ${prime.val[k]} ${prime.val[-1]}) )
case $? in
0) (( spcnt++ ))
(( spcnt <= NUM_STRONG )) && strbuff+="${prime.val[j]}, "
(( i >= GOAL1 )) && (( ! sflg )) && (( goal1_strong = spcnt - 1 )) && (( sflg = 1 ))
;;
1) (( wpcnt++ ))
(( wpcnt <= NUM_WEAK )) && weabuff+="${prime.val[j]}, "
(( i >= GOAL1 )) && (( ! wflg )) && (( goal1_weak = wpcnt - 1 )) && (( wflg = 1 ))
;;
99) (( bpcnt++ ))
;;
esac
done
printf "Total primes under %d = %d\n\n" $MAX_INT ${#prime.val[*]}
printf "First %d Strong Primes are: %s\n\n" $NUM_STRONG "${strbuff%,*}"
printf "Number of Strong Primes under %d is: %d\n" $GOAL1 ${goal1_strong}
printf "Number of Strong Primes under %d is: %d\n\n\n" $MAX_INT ${spcnt}
printf "First %d Weak Primes are: %s\n\n" $NUM_WEAK "${weabuff%,*}"
printf "Number of Weak Primes under %d is: %d\n" $GOAL1 ${goal1_weak}
printf "Number of Weak Primes under %d is: %d\n\n\n" $MAX_INT ${wpcnt}
printf "Number of Balanced Primes under %d is: %d\n\n\n" $MAX_INT ${bpcnt}</syntaxhighlight>
{{out}}<pre>
Total primes under 10000000 = 664579
First 36 Strong Primes are: 11, 17, 29, 37, 41, 59, 67, 71, 79, 97, 101, 107, 127, 137, 149, 163, 179, 191, 197, 223, 227, 239, 251, 269, 277, 281, 307, 311, 331, 347, 367, 379, 397, 419, 431, 439
Number of Strong Primes under 1000000 is: 37723
Number of Strong Primes under 10000000 is: 320991
First 37 Weak Primes are: 3, 7, 13, 19, 23, 31, 43, 47, 61, 73, 83, 89, 103, 109, 113, 131, 139, 151, 167, 181, 193, 199, 229, 233, 241, 271, 283, 293, 313, 317, 337, 349, 353, 359, 383, 389, 401
Number of Weak Primes under 1000000 is: 37779
Number of Weak Primes under 10000000 is: 321749
Number of Balanced Primes under 10000000 is: 21837</pre>
=={{header|Lua}}==
This could be made faster but favours readability. It runs in about 3.3 seconds in LuaJIT on a 2.8 GHz core.
<
function primeList (n)
local function isPrime (x)
Line 1,071 ⟶ 1,655:
for i = 1, 37 do io.write(weak[i] .. " ") end
print("\n\nThere are " .. wCount .. " weak primes below one million.")
print("\nThere are " .. #weak .. " weak primes below ten million.")</
{{out}}
<pre>The first 36 strong primes are:
Line 1,089 ⟶ 1,673:
=={{header|Maple}}==
<
holder := false;
if isprime(n) and 1/2*prevprime(n) + 1/2*nextprime(n) < n then
Line 1,132 ⟶ 1,716:
countStrong(10000000)
countWeak(1000000)
countWeak(10000000)</
{{Out}}
<pre>[11, 17, 29, 37, 41, 59, 67, 71, 79, 97, 101, 107, 127, 137, 149, 163, 179, 191, 197, 223, 227, 239, 251, 269, 277, 281, 307, 311, 331, 347, 367, 379, 397, 419, 431, 439]
Line 1,140 ⟶ 1,724:
37780
321750</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">p = Prime[Range[PrimePi[10^3]]];
SequenceCases[p, ({a_, b_, c_}) /; (a + c < 2 b) :> b, 36, Overlaps -> True]
SequenceCases[p, ({a_, b_, c_}) /; (a + c > 2 b) :> b, 37, Overlaps -> True]
p = Prime[Range[PrimePi[10^6] + 1]];
Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] < 2 #[[2]] &]]
Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] > 2 #[[2]] &]]
p = Prime[Range[PrimePi[10^7] + 1]];
Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] < 2 #[[2]] &]]
Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] > 2 #[[2]] &]]</syntaxhighlight>
{{out}}
<pre>{11,17,29,37,41,59,67,71,79,97,101,107,127,137,149,163,179,191,197,223,227,239,251,269,277,281,307,311,331,347,367,379,397,419,431,439}
{3,7,13,19,23,31,43,47,61,73,83,89,103,109,113,131,139,151,167,181,193,199,229,233,241,271,283,293,313,317,337,349,353,359,383,389,401}
37723
37780
320991
321750</pre>
=={{header|Nim}}==
<syntaxhighlight lang="nim">import math, strutils
const
M = 10_000_000
N = M + 19 # Maximum value for sieve.
# Fill sieve of Erathosthenes.
var comp: array[2..N, bool] # True means composite; default is prime.
for n in countup(3, sqrt(N.toFloat).int, 2):
if not comp[n]:
for k in countup(n * n, N, 2 * n):
comp[k] = true
# Build list of primes.
var primes = @[2]
for n in countup(3, N, 2):
if not comp[n]:
primes.add n
if primes[^1] < M: quit "Not enough primes: please, increase value of N."
# Build lists of strong and weak primes.
var strongPrimes, weakPrimes: seq[int]
for i in 1..<primes.high:
let p = primes[i]
if p shl 1 > primes[i - 1] + primes[i + 1]:
strongPrimes.add p
elif p shl 1 < primes[i - 1] + primes[i + 1]:
weakPrimes.add p
when isMainModule:
proc count(list: seq[int]; max: int): int =
## Return the count of values less than "max".
for p in list:
if p >= max: break
inc result
echo "First 36 strong primes:"
echo " ", strongPrimes[0..35].join(" ")
echo "Count of strong primes below 1_000_000: ", strongPrimes.count(1_000_000)
echo "Count of strong primes below 10_000_000: ", strongPrimes.count(10_000_000)
echo()
echo "First 37 weak primes:"
echo " ", weakPrimes[0..36].join(" ")
echo "Count of weak primes below 1_000_000: ", weakPrimes.count(1_000_000)
echo "Count of weak primes below 10_000_000: ", weakPrimes.count(10_000_000)</syntaxhighlight>
{{out}}
<pre>First 36 strong primes:
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
Count of strong primes below 1_000_000: 37723
Count of strong primes below 10_000_000: 320991
First 37 weak primes:
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
Count of weak primes below 1_000_000: 37780
Count of weak primes below 10_000_000: 321750</pre>
=={{header|Pascal}}==
Line 1,147 ⟶ 1,811:
If deltaAfter < deltaBefore than a strong prime is found.
<
{$IFNDEF FPC}
{$AppType CONSOLE}
Line 1,315 ⟶ 1,979:
WeakOut(37);
CntWeakStrong10(CntWs);
end.</
{{Out}}
<pre>
Line 1,338 ⟶ 2,002:
{{trans|Raku}}
{{libheader|ntheory}}
<
sub comma {
Line 1,365 ⟶ 2,029:
print "Count of $type primes <= @{[comma $c1]}: " . comma below($c1,@$pr) . "\n";
print "Count of $type primes <= @{[comma $c2]}: " . comma scalar @$pr . "\n";
}</
{{out}}
<pre>
Line 1,385 ⟶ 2,049:
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">strong</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{},</span> <span style="color: #000000;">weak</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">get_maxprime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1e14</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- (ie idx of primes < (sqrt(1e14)==1e7), bar 1st)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">p</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">compare</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,(</span><span style="color: #7060A8;">get_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)+</span><span style="color: #7060A8;">get_prime</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=+</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">strong</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">p</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">weak</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">p</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first thirty six strong primes: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">strong</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">36</span><span style="color: #0000FF;">],</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">", "</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first thirty seven weak primes: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span> <span style="color: #000000;">weak</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">37</span><span style="color: #0000FF;">],</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">", "</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"There are %,d strong primes below %,d and %,d below %,d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1e6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">strong</span><span style="color: #0000FF;">))-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e6</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">strong</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1e7</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"There are %,d weak primes below %,d and %,d below %,d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">binary_search</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1e6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">weak</span><span style="color: #0000FF;">))-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1e6</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span> <span style="color: #000000;">weak</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1e7</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
The first
The first
</pre>
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">#MAX=10000000+20
Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte)
Global NewList Primes.i()
Global NewList Strong.i()
Global NewList Weak.i()
For n=2 To Sqr(#MAX)+1 : If P(n) : m=n*n : While m<=#MAX : P(m)=0 : m+n : Wend : EndIf : Next
For i=2 To #MAX : If p(i) : AddElement(Primes()) : Primes()=i : EndIf : Next
If FirstElement(Primes())
pp=Primes()
While NextElement(Primes())
ap=Primes()
If NextElement(Primes()) : np=Primes() : Else : Break : EndIf
If ap>(pp+np)/2.0 : AddElement(Strong()) : Strong()=ap : If ap<1000000 : c1+1 : EndIf : EndIf
If ap<(pp+np)/2.0 : AddElement(Weak()) : Weak()=ap : If ap<1000000 : c2+1 : EndIf : EndIf
PreviousElement(Primes()) : pp=Primes()
Wend
EndIf
OpenConsole()
If FirstElement(Strong())
PrintN("First 36 strong primes:")
Print(Str(Strong())+" ")
For i=2 To 36 : If NextElement(Strong()) : Print(Str(Strong())+" ") : Else : Break : EndIf : Next
PrintN("")
EndIf
PrintN("Number of strong primes below 1'000'000 = "+FormatNumber(c1,0,".","'"))
PrintN("Number of strong primes below 10'000'000 = "+FormatNumber(ListSize(Strong()),0,".","'"))
If FirstElement(Weak())
PrintN("First 37 weak primes:")
Print(Str(Weak())+" ")
For i=2 To 37 : If NextElement(Weak()) : Print(Str(Weak())+" ") : Else : Break : EndIf : Next
PrintN("")
EndIf
PrintN("Number of weak primes below 1'000'000 = "+FormatNumber(c2,0,".","'"))
PrintN("Number of weak primes below 10'000'000 = "+FormatNumber(ListSize(Weak()),0,".","'"))
Input()</syntaxhighlight>
{{out}}
<pre>First 36 strong primes:
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
Number of strong primes below 1'000'000 = 37'723
Number of strong primes below 10'000'000 = 320'991
First 37 weak primes:
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
Number of weak primes below 1'000'000 = 37'780
Number of weak primes below 10'000'000 = 321'750
</pre>
Line 1,415 ⟶ 2,125:
COmputes and shows the requested output then adds similar output for the "balanced" case where <code>prime(p) == [prime(p-1) + prime(p+1)] ÷ 2</code>.
<
def primesfrom2to(n):
Line 1,451 ⟶ 2,161:
print('\nTOTAL primes below 1,000,000:',
sum(1 for pr in p if pr < 1_000_000))
print('TOTAL primes below 10,000,000:', len(p))</
{{out}}
Line 1,474 ⟶ 2,184:
{{works with|Rakudo|2018.11}}
<syntaxhighlight lang="raku"
use Math::Primesieve;
Line 1,499 ⟶ 2,209:
say "Count of $type primes <= {comma 1e6}: ", comma +@pr[^(@pr.first: * > 1e6,:k)];
say "Count of $type primes <= {comma 1e7}: ", comma +@pr;
}</
{{out}}
<pre>First 36 strong primes:
Line 1,517 ⟶ 2,227:
=={{header|REXX}}==
<
parse arg N kind _ . 1 . okind; upper kind /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 36 /*Not specified? Then assume default.*/
Line 1,566 ⟶ 2,276:
else return 0 /*not " " " */
else if y>s then return add() /*is an strong prime.*/
return 0 /*not " " " */</
This REXX program makes use of '''LINESIZE''' REXX program (or
BIF) which is used to determine the screen width (or linesize) of the
Line 1,602 ⟶ 2,312:
<pre>
321,750 WEAK primes found below or equal to 10,000,000.
</pre>
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "stdlib.ring"
see "working..." + nl
p = 0
num = 0
pr1 = 37
pr2 = 38
limit1 = 457
limit2 = 1000000
limit3 = 10000000
primes = []
see "first 36 strong primes:" + nl
while true
p = p + 1
if isprime(p)
if p < limit1
add(primes,p)
else
exit
ok
ok
end
ln = len(primes)
for n = 2 to ln-1
tmp = (primes[n-1] + primes[n+1])/2
if primes[n] > tmp
num = num + 1
if num < pr1
see " " + primes[n]
ok
ok
next
see nl + "first 37 weak primes:" + nl
num = 0
ln = len(primes)
for n = 2 to ln-1
tmp = (primes[n-1] + primes[n+1])/2
if primes[n] < tmp
num = num + 1
if num < pr2
see " " + primes[n]
ok
ok
next
p = 0
primes = []
while true
p = p + 1
if isprime(p)
if p < limit3
add(primes,p)
else
exit
ok
ok
end
primes2 = 0
primes3 = 0
ln = len(primes)
for n = 2 to ln-1
tmp = (primes[n-1] + primes[n+1])/2
if primes[n] > tmp
if primes[n] < limit2
primes2 = primes2 + 1
ok
if primes[n] < limit3
primes3 = primes3 + 1
else
exit
ok
ok
next
see nl
see "strong primes below 1,000,000: " + primes2 + nl
see "strong primes below 10,000,000: " + primes3 + nl
primes2 = 0
primes3 = 0
ln = len(primes)
for n = 2 to ln-1
tmp = (primes[n-1] + primes[n+1])/2
if primes[n] < tmp
if primes[n] < limit2
primes2 = primes2 + 1
ok
if primes[n] < limit3
primes3 = primes3 + 1
else
exit
ok
ok
next
see nl
see "weak primes below 1,000,000: " + primes2 + nl
see "weak primes below 10,000,000: " + primes3 + nl
</syntaxhighlight>
Output:
<pre>
first 36 strong primes:
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
first 37 weak primes:
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
strong primes below 1,000,000: 37723
strong primes below 10,000,000: 320991
weak primes below 1,000,000: 37780
weak primes below 10,000,000: 321750
</pre>
=={{header|Ruby}}==
<
strong_gen = Enumerator.new{|y| Prime.each_cons(3){|a,b,c|y << b if a+c-b<b} }
Line 1,624 ⟶ 2,453:
puts "#{strongs} strong primes and #{weaks} weak primes below #{limit}."
end
</syntaxhighlight>
{{out}}
<pre>First 36 strong primes:
Line 1,634 ⟶ 2,463:
37723 strong primes and 37780 weak primes below 1000000.
320991 strong primes and 321750 weak primes below 10000000.
</pre>
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn is_prime(n: i32) -> bool {
for i in 2..n {
if i * i > n {
return true;
}
if n % i == 0 {
return false;
}
}
n > 1
}
fn next_prime(n: i32) -> i32 {
for i in (n+1).. {
if is_prime(i) {
return i;
}
}
0
}
fn main() {
let mut n = 0;
let mut prime_q = 5;
let mut prime_p = 3;
let mut prime_o = 2;
print!("First 36 strong primes: ");
while n < 36 {
if prime_p > (prime_o + prime_q) / 2 {
print!("{} ",prime_p);
n += 1;
}
prime_o = prime_p;
prime_p = prime_q;
prime_q = next_prime(prime_q);
}
println!("");
while prime_p < 1000000 {
if prime_p > (prime_o + prime_q) / 2 {
n += 1;
}
prime_o = prime_p;
prime_p = prime_q;
prime_q = next_prime(prime_q);
}
println!("strong primes below 1,000,000: {}", n);
while prime_p < 10000000 {
if prime_p > (prime_o + prime_q) / 2 {
n += 1;
}
prime_o = prime_p;
prime_p = prime_q;
prime_q = next_prime(prime_q);
}
println!("strong primes below 10,000,000: {}", n);
n = 0;
prime_q = 5;
prime_p = 3;
prime_o = 2;
print!("First 36 weak primes: ");
while n < 36 {
if prime_p < (prime_o + prime_q) / 2 {
print!("{} ",prime_p);
n += 1;
}
prime_o = prime_p;
prime_p = prime_q;
prime_q = next_prime(prime_q);
}
println!("");
while prime_p < 1000000 {
if prime_p < (prime_o + prime_q) / 2 {
n += 1;
}
prime_o = prime_p;
prime_p = prime_q;
prime_q = next_prime(prime_q);
}
println!("weak primes below 1,000,000: {}", n);
while prime_p < 10000000 {
if prime_p < (prime_o + prime_q) / 2 {
n += 1;
}
prime_o = prime_p;
prime_p = prime_q;
prime_q = next_prime(prime_q);
}
println!("weak primes below 10,000,000: {}", n);
}</syntaxhighlight>
<pre>
First 36 strong primes: 11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
strong primes below 1,000,000: 37723
strong primes below 10,000,000: 320991
First 36 weak primes: 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
weak primes below 1,000,000: 37779
weak primes below 10,000,000: 321749
</pre>
=={{header|Scala}}==
This example works entirely with lazily evaluated lists. It starts with a list of primes, and generates a sliding iterator that looks at each triplet of primes. Lists of strong and weak primes are built by applying the given filters then selecting the middle term from each triplet.
<
def main(args: Array[String]): Unit = {
val bnd = 1000000
Line 1,655 ⟶ 2,590:
def primeTrips: Iterator[LazyList[Int]] = primes.sliding(3)
def primes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(n => !Iterator.range(3, math.sqrt(n).toInt + 1, 2).exists(n%_ == 0))
}</
{{out}}
Line 1,668 ⟶ 2,603:
=={{header|Sidef}}==
{{trans|Raku}}
<
var (*strong, *weak, *balanced)
Line 1,690 ⟶ 2,625:
say ("Count of #{type} primes <= #{c1.commify}: ", pr.first_index { _ > 1e6 }.commify)
say ("Count of #{type} primes <= #{c2.commify}: " , pr.len.commify)
}</
{{out}}
<pre>
Line 1,707 ⟶ 2,642:
Count of balanced primes <= 1,000,000: 2,994
Count of balanced primes <= 10,000,000: 21,837
</pre>
=={{header|Swift}}==
<syntaxhighlight lang="swift">import Foundation
class PrimeSieve {
var composite: [Bool]
init(size: Int) {
composite = Array(repeating: false, count: size/2)
var p = 3
while p * p <= size {
if !composite[p/2 - 1] {
let inc = p * 2
var q = p * p
while q <= size {
composite[q/2 - 1] = true
q += inc
}
}
p += 2
}
}
func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
if (number & 1) == 0 {
return number == 2
}
return !composite[number/2 - 1]
}
}
func commatize(_ number: Int) -> String {
let n = NSNumber(value: number)
return NumberFormatter.localizedString(from: n, number: .decimal)
}
let limit1 = 1000000
let limit2 = 10000000
class PrimeInfo {
let maxPrint: Int
var count1: Int
var count2: Int
var primes: [Int]
init(maxPrint: Int) {
self.maxPrint = maxPrint
count1 = 0
count2 = 0
primes = []
}
func addPrime(prime: Int) {
count2 += 1
if prime < limit1 {
count1 += 1
}
if count2 <= maxPrint {
primes.append(prime)
}
}
func printInfo(name: String) {
print("First \(maxPrint) \(name) primes: \(primes)")
print("Number of \(name) primes below \(commatize(limit1)): \(commatize(count1))")
print("Number of \(name) primes below \(commatize(limit2)): \(commatize(count2))")
}
}
var strongPrimes = PrimeInfo(maxPrint: 36)
var weakPrimes = PrimeInfo(maxPrint: 37)
let sieve = PrimeSieve(size: limit2 + 100)
var p1 = 2, p2 = 3, p3 = 5
while p2 < limit2 {
if sieve.isPrime(number: p3) {
let diff = p1 + p3 - 2 * p2
if diff < 0 {
strongPrimes.addPrime(prime: p2)
} else if diff > 0 {
weakPrimes.addPrime(prime: p2)
}
p1 = p2
p2 = p3
}
p3 += 2
}
strongPrimes.printInfo(name: "strong")
weakPrimes.printInfo(name: "weak")</syntaxhighlight>
{{out}}
<pre>
First 36 strong primes: [11, 17, 29, 37, 41, 59, 67, 71, 79, 97, 101, 107, 127, 137, 149, 163, 179, 191, 197, 223, 227, 239, 251, 269, 277, 281, 307, 311, 331, 347, 367, 379, 397, 419, 431, 439]
Number of strong primes below 1,000,000: 37,723
Number of strong primes below 10,000,000: 320,991
First 37 weak primes: [3, 7, 13, 19, 23, 31, 43, 47, 61, 73, 83, 89, 103, 109, 113, 131, 139, 151, 167, 181, 193, 199, 229, 233, 241, 271, 283, 293, 313, 317, 337, 349, 353, 359, 383, 389, 401]
Number of weak primes below 1,000,000: 37,780
Number of weak primes below 10,000,000: 321,750
</pre>
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./math" for Int
import "./fmt" for Fmt
var primes = Int.primeSieve(1e7 + 19) // next prime above 10 million
var strong = []
var weak = []
for (p in 1...primes.count-1) {
if (primes[p] > (primes[p-1] + primes[p+1]) / 2) {
strong.add(primes[p])
} else if (primes[p] < (primes[p-1] + primes[p+1]) / 2) {
weak.add(primes[p])
}
}
System.print("The first 36 strong primes are:")
Fmt.print("$d", strong.take(36))
Fmt.print("\nThe count of the strong primes below $,d is $,d.", 1e6, strong.count{ |n| n < 1e6 })
Fmt.print("\nThe count of the strong primes below $,d is $,d.", 1e7, strong.count{ |n| n < 1e7 })
System.print("\nThe first 37 weak primes are:")
Fmt.print("$d", weak.take(37))
Fmt.print("\nThe count of the weak primes below $,d is $,d.", 1e6, weak.count{ |n| n < 1e6 })
Fmt.print("\nThe count of the weak primes below $,d is $,d.", 1e7, weak.count{ |n| n < 1e7 })</syntaxhighlight>
{{out}}
<pre>
The first 36 strong primes are:
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
The count of the strong primes below 1,000,000 is 37,723.
The count of the strong primes below 10,000,000 is 320,991.
The first 37 weak primes are:
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
The count of the weak primes below 1,000,000 is 37,780.
The count of the weak primes below 10,000,000 is 321,750.
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">proc NumOut(Num); \Output positive integer with commas
int Num, Dig, Cnt;
[Cnt:= [0];
Num:= Num/10;
Dig:= rem(0);
Cnt(0):= Cnt(0)+1;
if Num then NumOut(Num);
Cnt(0):= Cnt(0)-1;
ChOut(0, Dig+^0);
if rem(Cnt(0)/3)=0 & Cnt(0) then ChOut(0, ^,);
];
func IsPrime(N); \Return 'true' if odd N > 2 is prime
int N, I;
[for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
int StrongCnt, WeakCnt, StrongCnt0, WeakCnt0, Strongs(36), Weaks(37);
int N, P0, P1, P2, T;
[StrongCnt:= 0; WeakCnt:= 1;
Weaks(0):= 3;
N:= 7; P1:= 3; P2:= 5; \handles unique case where (2+5)/2 = 3.5
repeat if IsPrime(N) then
[P0:= P1; P1:= P2; P2:= N;
T:= (P0+P2)/2;
if P1 > T then
[if StrongCnt < 36 then Strongs(StrongCnt):= P1;
StrongCnt:= StrongCnt+1;
];
if P1 < T then
[if WeakCnt < 37 then Weaks(WeakCnt):= P1;
WeakCnt:= WeakCnt+1;
];
];
if P1 < 1_000_000 then
[StrongCnt0:= StrongCnt; WeakCnt0:= WeakCnt];
N:= N+2;
until P1 >= 10_000_000;
Text(0, "First 36 strong primes:^M^J");
for N:= 0 to 36-1 do
[NumOut(Strongs(N)); ChOut(0, ^ )];
Text(0, "^M^JStrong primes below 1,000,000: ");
NumOut(StrongCnt0);
Text(0, "^M^JStrong primes below 10,000,000: ");
NumOut(StrongCnt);
Text(0, "^M^JFirst 37 weak primes:^M^J");
for N:= 0 to 37-1 do
[NumOut(Weaks(N)); ChOut(0, ^ )];
Text(0, "^M^JWeak primes below 1,000,000: ");
NumOut(WeakCnt0);
Text(0, "^M^JWeak primes below 10,000,000: ");
NumOut(WeakCnt);
CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
First 36 strong primes:
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
Strong primes below 1,000,000: 37,723
Strong primes below 10,000,000: 320,991
First 37 weak primes:
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
Weak primes below 1,000,000: 37,780
Weak primes below 10,000,000: 321,751
</pre>
Line 1,714 ⟶ 2,870:
[[Extensible prime generator#zkl]] could be used instead.
<
const N=1e7;
Line 1,726 ⟶ 2,882:
}
ps.pop(0); ps.append(pw.nextPrime().toInt());
}while(pn<=N);</
<
println("First %d %s primes:\n%s".fmt(psz,nm,list[0,psz].concat(" ")));
println("Count of %s primes <= %,10d: %,8d"
.fmt(nm,1e6,list.reduce('wrap(s,p){ s + (p<=1e6) },0)));
println("Count of %s primes <= %,10d: %,8d\n".fmt(nm,1e7,list.len()));
}</
{{out}}
<pre>
|