Descending primes: Difference between revisions

Content added Content deleted
No edit summary
Line 361: Line 361:
{{out}}
{{out}}
Same as C#
Same as C#

=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}


<syntaxhighlight lang="Delphi">
type TProgress = procedure(Percent: integer);


function IsPrime(N: integer): boolean;
{Optimised prime test - about 40% faster than the naive approach}
var I,Stop: integer;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
begin
I:=5;
Stop:=Trunc(sqrt(N));
Result:=False;
while I<=Stop do
begin
if ((N mod I) = 0) or ((N mod (i + 2)) = 0) then exit;
Inc(I,6);
end;
Result:=True;
end;
end;

function IsDescending(N: integer): boolean;
{Determine if each digit is less than previous, left to right}
var S: string;
var I: integer;
begin
Result:=False;
S:=IntToStr(N);
for I:=1 to Length(S)-1 do
if S[I]<=S[I+1] then exit;
Result:=True;
end;


procedure ShowDescendingPrimes(Memo: TMemo; Prog: TProgress);
{Write Descending primes up to 123,456,789 }
{The Optional progress }
var I,Cnt: integer;
var S: string;
const Max = 123456789;
begin
if Assigned(Prog) then Prog(0);
S:='';
Cnt:=0;
for I:=2 to Max do
begin
if ((I mod 1000000)=0) and Assigned(Prog) then Prog(Trunc(100*(I/Max)));
if IsDescending(I) and IsPrime(I) then
begin
S:=S+Format('%12.0n', [I*1.0]);
Inc(Cnt);
if (Cnt mod 10)=0 then
begin
Memo.Lines.Add(S);
S:='';
end;
end;
end;
if S<>'' then Memo.Lines.Add(S);
Memo.Lines.Add('Descending Primes Found: '+IntToStr(Cnt));
end;



</syntaxhighlight>
{{out}}
<pre>
2 3 5 7 31 41 43 53 61 71
73 83 97 421 431 521 541 631 641 643
653 743 751 761 821 853 863 941 953 971
983 5,431 6,421 6,521 7,321 7,541 7,621 7,643 8,431 8,521
8,543 8,641 8,731 8,741 8,753 8,761 9,421 9,431 9,521 9,631
9,643 9,721 9,743 9,851 9,871 75,431 76,421 76,541 76,543 86,531
87,421 87,541 87,631 87,641 87,643 94,321 96,431 97,651 98,321 98,543
98,621 98,641 98,731 764,321 865,321 876,431 975,421 986,543 987,541 987,631
8,764,321 8,765,321 9,754,321 9,875,321 97,654,321 98,764,321 98,765,431
Descending Primes Found: 87

</pre>



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