Rare numbers: Difference between revisions

15,144 bytes added ,  15 days ago
m (→‎advanced: syntax coloured)
 
(17 intermediate revisions by 11 users not shown)
Line 26:
:*   author's  website:   [http://www.shyamsundergupta.com/rare.html rare numbers]   by Shyam Sunder Gupta.     (lots of hints and some observations).
<br><br>
 
=={{header|ALGOL 68}}==
{{Trans|FreeBASIC}}
which is
{{Trans|Phix}}
(naive version)
<syntaxhighlight lang="algol68">
PROC revn = ( LONG INT na, nda )LONG INT:
BEGIN
LONG INT n := na, nd := nda, r := 0, i := 0;
WHILE i +:= 1;
i <= nd
DO
r *:= 10 +:= ( n MOD 10 );
n OVERAB 10
OD;
r
END # revn # ;
 
LONG INT nd := 2, count := 0, lim := 90, n := 20;
 
DO
n +:= 1;
LONG INT r = revn( n, nd );
IF r < n THEN
LONG INT s = n + r, d = n - r;
IF IF ODD nd
THEN d MOD 1089 = 0
ELSE s MOD 121 = 0
FI
THEN
IF LONG REAL root s = long sqrt( s );
root s = ENTIER root s
THEN
IF LONG REAL root d = long sqrt( d );
root d = ENTIER root d
THEN
count +:= 1;
print( ( whole( count, 0 ), ": ", whole( n, 0 ), newline ) );
IF count >= 5 THEN stop FI
FI
FI
FI;
IF n = lim
THEN
lim *:= 10;
nd +:= 1;
n := ( lim OVER 9 ) * 2
FI
FI
OD
</syntaxhighlight>
{{out}}
<pre>
1: 65
2: 621770
3: 281089082
4: 2022652202
5: 2042832002
</pre>
 
=={{header|C sharp|C#}}==
Line 31 ⟶ 91:
{{trans|Go}}
Converted to unsigned longs in order to reach 19 digits.
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 125 ⟶ 185:
count = 0; foreach (var rare in res) WriteLine("{0,2}:{1,27:n0}", ++count, rare);
if (System.Diagnostics.Debugger.IsAttached) ReadKey(); }
}</langsyntaxhighlight>
{{out}}
Results from a core i7-7700 @ 3.6Ghz. This C# version isn't as fast as the Go version using the same hardware. C# computes up to 17, 18 and 19 digits in under 9 minutes, 1 2/3 hours and over 2 1/2 hours respectively. (Go is about 6 minutes, 1 1/4 hours, and under 2 hours).
Line 304 ⟶ 364:
===Quicker===
Along the lines of the C++ version. Computing the possible squares for the sums and differences, then comparing them together and reporting the ones that have a proper forward, reverse result. To save computation time, some shortcuts have been taken to avoid generating many non-square numbers. <br/><br/>Update, added computation of digital root, which increased performance a few percentage points. Interestingly, the digital root is always zero for the ''difference list of squares'', so no advantage is given by tracking it. Only the ''sum list of squares'' benefits from calculating the digital root of the partial sum and using an abbreviated sequence for the last round of permutation.
<langsyntaxhighlight lang="csharp">using static System.Math; // for Sqrt()
using System.Collections.Generic; // for List<>, .Count
using System.Linq; // for .Last(), .ToList()
Line 489 ⟶ 549:
static bool IsRev(int nd, ulong f, ulong r) { nd--; return f / (ulong)p[nd] != r % 10 ? false : (nd < 1 ? true : IsRev(nd, f % (ulong)p[nd], r / 10)); }
#endregion 19
}</langsyntaxhighlight>
{{out}}
Results on the core i7-7700 @ 3.6Ghz.
Line 577 ⟶ 637:
=={{header|C++}}==
===Calculate L and H independently===
<langsyntaxhighlight lang="cpp">
// Rare Numbers : Nigel Galloway - December 20th., 2019;
// Nigel Galloway/Enter your username - January 4th., 2021 (see discussion page.
Line 661 ⟶ 721:
for (int nd{2}; nd <= max; ++nd) Rare(nd);
}
</syntaxhighlight>
</lang>
{{out}}
Processor Intel(R) Core(TM) i5-1035G1 CPU @ 1.00GHz
Line 749 ⟶ 809:
</pre>
===20+ digits===
<langsyntaxhighlight lang="cpp">
// Rare Numbers : Nigel Galloway - December 20th., 2019
#include <iostream>
Line 794 ⟶ 854:
Rare(20);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 841 ⟶ 901:
{{trans|Go}}
Scaled down from the full duration showed in the go example because I got impatient and have not spent time figuring out where the inefficeny is.
<langsyntaxhighlight lang="d">import std.algorithm;
import std.array;
import std.conv;
Line 1,053 ⟶ 1,113:
writefln(" %2d: %25s", i + 1, commatize(rare));
}
}</langsyntaxhighlight>
{{out}}
<pre>Aggregate timings to process all numbers up to:
Line 1,153 ⟶ 1,213:
39: 8,650,327,689,541,457
40: 8,650,349,867,341,457</pre>
 
=={{header|EasyLang}}==
{{trans|Ring}}
<syntaxhighlight lang=easylang>
fastfunc next n .
while 1 = 1
n += 1
h = n
nrev = 0
while h > 0
nrev = nrev * 10 + h mod 10
h = h div 10
.
if sqrt (n + nrev) mod 1 = 0
if n - nrev >= 1 and sqrt (n - nrev) mod 1 = 0
return n
.
.
.
.
for cnt to 5
n = next n
print n
.
</syntaxhighlight>
 
 
=={{header|F_Sharp|F#}}==
===The Function===
This solution demonstrates the concept described in [[Talk:Rare_numbers#30_mins_not_30_years]]. It doesn't use [[Cartesian_product_of_two_or_more_lists#Extra_Credit]]
<langsyntaxhighlight lang="fsharp">
// Find all Rare numbers with a digits. Nigel Galloway: September 18th., 2019.
let rareNums a=
Line 1,169 ⟶ 1,255:
|_->if n>(pown 10L (a-1)) then for l in (if a%2=0 then [0L] else [0L..9L]) do let g=l*(pown 10L (a/2)) in if izPS (n+i+2L*g) then yield (i+g,n+g)}
fN [0L..9L] [] (a/2) |> Seq.collect(List.rev >> fG 0L 0L (pown 10L (a-1)) 1L)
</syntaxhighlight>
</lang>
 
===43 down===
<langsyntaxhighlight lang="fsharp">
let test n=
let t = System.Diagnostics.Stopwatch.StartNew()
Line 1,180 ⟶ 1,266:
 
[2..17] |> Seq.iter test
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,243 ⟶ 1,329:
Elapsed Time: 11275839 ms for length 17
</pre>
 
 
=={{header|FreeBASIC}}==
Made some changes and added a simple test to speed things up. Results in about 1 minute.
{{trans|Phix}}
<langsyntaxhighlight lang="freebasic">Function revn(n As ULongInt, nd As ULongInt) As ULongInt
Dim As ULongInt r
For i As UInteger = 1 To nd
Line 1,285 ⟶ 1,370:
Print
Print "Done"
Sleep</langsyntaxhighlight>
{{out}}
<pre>1: 65
Line 1,298 ⟶ 1,383:
 
As the algorithm used does not generate the Rare numbers in order, a sorted list is also printed.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,507 ⟶ 1,592:
fmt.Printf(" %2d: %25s\n", i+1, commatize(rare))
}
}</langsyntaxhighlight>
 
{{output}}
Line 1,688 ⟶ 1,773:
{{trans|C#}}
Twice as quick as the first Go version though, despite being a faithful translation, a little slower than the C# and VB.NET versions.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,234 ⟶ 2,319:
ftTime := formatTime(time.Since(tStart))
fmt.Printf("%2d: %s %s\n", nd, fbTime, ftTime)
}</langsyntaxhighlight>
 
{{out}}
Line 2,329 ⟶ 2,414:
 
Curiously, the C++ program itself when compiled with g++ 7.5.0 (-std=c++17 -O3) on the same machine (and incorporating the same improvements) completes in just over 21 minutes though I understand that when using other C++ compilers (clang, mingw) it's much faster than this.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,590 ⟶ 2,675:
bStart = time.Now() // restart block timing
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,675 ⟶ 2,760:
To use it to find rare numbers, one would simply apply it to each integer seriatim, and keep the numbers where its output is true (I.@:rare i. AS_HIGH_AS_YOU_WANT_TO_CHECK); but since these numbers are, well, rare, actually doing so would take a very long time.
 
<langsyntaxhighlight lang="j">rare =: ( np@:] *. (nbrPs rr) ) b10
np =: -.@:(-: |.) NB. Not palindromic
nbrPs =: > *. sdPs NB. n is Bigger than R and the perfect square constraint is satisfied
Line 2,681 ⟶ 2,766:
ps =: 0 = 1 | %: NB. Perfect square (integral sqrt)
rr =: 10&#.@:|. NB. Do note we do reverse the digits twice (once here, once in np)
b10 =: 10&#.^:_1 NB. Base 10 digits</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="j"> NB. From OEIS
R =: 65 621770 281089082 2022652202 2042832002 868591084757 872546974178 872568754178 6979302951885 20313693904202 20313839704202 20331657922202 20331875722202 20333875702202 40313893704200
rare"0 R
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="java">import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
Line 2,962 ⟶ 3,047:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Aggregate timings to process all numbers up to:
Line 3,065 ⟶ 3,150:
=={{header|Julia}}==
{{trans|Go}}
<langsyntaxhighlight lang="julia">using Formatting, Printf
 
struct Term
Line 3,238 ⟶ 3,323:
 
findrare()
</langsyntaxhighlight>{{out}}
Timings are on a 2.9 GHz i5 processor, 16 Gb RAM, under Windows 10.
<pre style="height:126ex;overflow:scroll">
Line 3,416 ⟶ 3,501:
=={{header|Kotlin}}==
{{trans|D}}
<langsyntaxhighlight lang="scala">import java.time.Duration
import java.time.LocalDateTime
import kotlin.math.sqrt
Line 3,653 ⟶ 3,738:
println(" %2d: %25s".format(i_rare.index + 1, commatize(i_rare.value)))
}
}</langsyntaxhighlight>
{{out}}
<pre>Aggregate timings to process all numbers up to:
Line 3,753 ⟶ 3,838:
39: 8,650,327,689,541,457
40: 8,650,349,867,341,457</pre>
 
=={{header|Lambdatalk}}==
Just coding the definition of a rare number without any optimization.
<syntaxhighlight lang="Scheme">
 
{def lt_israre
{lambda {:n}
{let { {:n :n}
{:r {W.reverse :n}}
} {if {and {> :n :r}
{isInt {sqrt {+ :n :r}}}
{isInt {sqrt {- :n :r}}}}
then :n
else}}}}
-> lt_israre
 
{S.map lt_israre {S.serie 1 700000}}
-> 65 621770 // computed in 7650ms
 
Testing:
 
{S.map lt_israre {S.serie 1 280000000}}
-> ... crushes Firefox working in my small iPad Pro.
 
And so I ask javascript some help:
 
LAMBDATALK.DICT["js_israres"] = function() {
var args = arguments[0].trim().split(" "),
i0 = Number( args[0] ),
i1 = Number( args[1] ),
a = [];
 
var israre = function(n) {
var r = Number( n.toString().split("").reverse().join("") );
return (n > r) && (Number.isInteger(Math.sqrt(n+r)))
&& (Number.isInteger(Math.sqrt(n-r)))
};
 
for (var i=i0; i < i1; i++)
if (israre(i)) a.push(i);
return a
};
 
Testing:
 
{js_israres 1 2050000000}
-> [65,621770,281089082,2022652202,2042832002]]
// computed in 784307ms ~ 13 minutes
 
Too slow to try to go further.
 
</syntaxhighlight>
 
=={{header|langur}}==
Line 3,759 ⟶ 3,896:
It could look something like the following (ignoring whatever optimizations the other examples are using), if it was fast enough. I did not have the time/processor to test finding the first 5. The .israre() function appears to return the right answer, tested with individual numbers.
 
<syntaxhighlight lang="langur">val .perfectsquare = fn(.n) { (.n ^/ 2) div 1 }
{{works with|langur|0.8.11}}
<lang langur>val .perfectsquare = f isInteger .n ^/ 2
 
val .israre = ffn(.n) {
val .r = reverse(.n)
if .n == .r: return false
Line 3,770 ⟶ 3,906:
}
 
val .findfirst = ffn(.max) {
for[=[]] .i = 0; len(_for) < .max; .i += 1 {
if .israre(.i) {
_for ~= [.i]
if len(_for) == .max: break
}
}
Line 3,780 ⟶ 3,915:
 
# if you have the time...
writeln "the first 5 rare numbers: ", .findfirst(5)</langsyntaxhighlight>
 
=={{header|Lua}}==
With 0.8.11, the built-in reverse() function will flip the digits of a number. Without this, you could write your own function to do so as follows (if not passed any negative numbers).
{{Trans|Phix|niave version, via FreeBASIC and Algol 68}}
<syntaxhighlight lang="lua">
do -- find the first five rare numbers
 
local function revn ( na )
<lang langur>val .reverse = f toNumber join reverse split .n</lang>
local n, r = na, 0
while n > 0 do
r = r * 10 r = r + ( n % 10 )
n = math.floor( n / 10 )
end
return r
end -- revn
 
local nd, count, lim, n = 2, 0, 90, 20
local oddNd = nd % 2 == 1
while true do
n = n + 1
local r = revn( n )
if r < n then
local s, d = n + r, n - r
local tryThis = false
if oddNd
then tryThis = d % 1089 == 0
else tryThis = s % 121 == 0
end
if tryThis then
local rootS = math.sqrt( s )
if rootS == math.floor(rootS )
then
local rootD = math.sqrt( d )
if rootD == math.floor( rootD )
then
count = count + 1
io.write( count, ": ", n, "\n" )
if count >= 5 then os.exit() end
end
end
end
if n == lim
then
lim = lim * 10
nd = nd + 1
oddNd = not oddNd
n = math.floor( lim / 9 ) * 2
end
end
end
end
</syntaxhighlight>
{{out}}
<pre>
1: 65
2: 621770
3: 281089082
4: 2022652202
5: 2042832002
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">c = Compile[{{k, _Integer}},
Module[{out = {0}, start = 0, stop = 0, rlist = {0}, r = 0,
sum = 0.0, diff = 0.0, imax = 8, step = 10},
Line 3,835 ⟶ 4,025:
]
];
Rest[c[9]] (*takes about 310 sec*)</langsyntaxhighlight>
{{out}}
<pre>{65, 621770, 281089082, 2022652202, 2042832002}</pre>
Line 3,842 ⟶ 4,032:
{{trans|Go}}
Translation of the second Go version, limited to 18 digits.
<langsyntaxhighlight Nimlang="nim">import algorithm, math, strformat, times
 
type Llst = seq[seq[int]]
Line 4,081 ⟶ 4,271:
nd1 = nd
inc nd
odd = not odd</langsyntaxhighlight>
 
{{out}}
Line 4,156 ⟶ 4,346:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Rare_numbers
Line 4,175 ⟶ 4,365:
++$count >= 5 and exit;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,187 ⟶ 4,377:
=={{header|Phix}}==
===naive===
Ridiculously slow, 90s just for the first 3, though twice as fast (41s) under p2js.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function revn(atom n, integer nd)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
atom r = 0
<span style="color: #008080;">function</span> <span style="color: #000000;">revn</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">nd</span><span style="color: #0000FF;">)</span>
for i=1 to nd do
<span style="color: #004080;">atom</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
r = r*10+remainder(n,10)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">nd</span> <span style="color: #008080;">do</span>
n = floor(n/10)
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">*</span><span style="color: #000000;">10</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
return r
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">r</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
integer nd = 2, count = 0
atom lim = 99, n = 9, t0 = time()
<span style="color: #004080;">integer</span> <span style="color: #000000;">nd</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
while true do
<span style="color: #004080;">atom</span> <span style="color: #000000;">lim</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">99</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span>
n += 1
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
atom r = revn(n,nd)
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if r<n then
<span style="color: #004080;">atom</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">revn</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nd</span><span style="color: #0000FF;">)</span>
atom s = n+r,
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><</span><span style="color: #000000;">n</span> <span style="color: #008080;">then</span>
d = n-r
<span style="color: #004080;">atom</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span>
if s=power(floor(sqrt(s)),2)
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">r</span>
and d=power(floor(sqrt(d)),2) then
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
count += 1
<span style="color: #008080;">and</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
?{count,n,elapsed(time()-t0)}
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if count=3 then exit end if
<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;">"%d: %d (%s)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)})</span>
end if
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if n=lim then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
-- ?{"lim",lim,elapsed(time()-t0)}
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">lim</span> <span style="color: #008080;">then</span>
lim = lim*10+9
<span style="color: #000080;font-style:italic;">-- ?{"lim",lim,elapsed(time()-t0)}</span>
nd += 1
<span style="color: #000000;">lim</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">lim</span><span style="color: #0000FF;">*</span><span style="color: #000000;">10</span><span style="color: #0000FF;">+</span><span style="color: #000000;">9</span>
end if
<span style="color: #000000;">nd</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
end while</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 4,233 ⟶ 4,426:
for over 30% of the run time. Improvements welcome: run p -d test, examine the list.asm produced from this source, and discuss or
make suggestions on [[User_talk:Petelomax|my talk page]].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">maxDigits</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">10</span><span style="color: #0000FF;">:</span><span style="color: #000000;">15</span><span style="color: #0000FF;">)</span>
Line 4,472 ⟶ 4,665:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,521 ⟶ 4,714:
A simple implementation, just to show how elegant python can be. Searches up to 10^11 in about 3hours w/ pypy on my Intel Core i5.
 
<syntaxhighlight lang="python">
<lang Python>
# rare.py
# find rare numbers
Line 4,558 ⟶ 4,751:
main()
 
</syntaxhighlight>
</lang>
===hodgepodge optimized===
A mess of code that can return the first 5 rare numbers in 1m19s on a i7-7700k using pypy3.9.
 
<syntaxhighlight lang="python">
# rare.py
# by xing216
 
import time as t
from functools import cache
 
@cache
def isSquare(n: int) ->bool:
if n < 0:
return False
if n == 0:
return True
while n&3 == 0:
n=n>>2
if n&7 != 1:
return False
if n==1:
return True
c = n%10
if c in {3, 7}:
return False
if n % 7 in {3, 5, 6}:
return False
if n % 9 in {2,3,5,6,8}:
return False
if n % 13 in {2,5,6,7,8,11}:
return False
if c == 5:
if (n//10)%10 != 2:
return False
if (n//100)%10 not in {0,2,6}:
return False
if (n//100)%10 == 6:
if (n//1000)%10 not in {0,5}:
return False
else:
if (n//10)%4 != 0:
return False
s = (len(str(n))-1) // 2
x = (10**s) * 4
A = {x, n}
while x * x != n:
x = (x + (n // x)) >> 1
if x in A:
return False
A.add(x)
return True
 
@cache
def main() -> None:
r = 1
start = t.time()
while True:
strr = str(r)
if int(strr[0]) % 2 != 0:
r += int('1' + (len(strr)-1)*'0' )
r1 = int(strr[::-1])
x = r + r1
y = r - r1
if isSquare(x) and isSquare(y) and r != r1:
print(f'success: {r} ~{t.time()-start}s')
r+=1
if __name__ == '__main__':
main()
 
</syntaxhighlight>
 
=={{header|Quackery}}==
Line 4,571 ⟶ 4,833:
On the other hand; code development time, less than five minutes. :-)
 
<langsyntaxhighlight Quackerylang="quackery">[ dup 1
[ 2dup > while
+ 1 >>
Line 4,605 ⟶ 4,867:
2drop ] is echorarenums ( n --> b )
5 echorarenums</langsyntaxhighlight>
 
{{Out}}
Line 4,612 ⟶ 4,874:
621770
281089082</pre>
 
=={{header|Racket}}==
===naive===
<syntaxhighlight lang="racket" line>; 20231024 Racket programming naive solution
#lang racket
(require control)
(require text-block/text)
 
(define (is-palindrome n)
(define (digit-list n)
(if (zero? n)
'()
(cons (remainder n 10) (digit-list (quotient n 10)))))
(define (reverse-list lst)
(if (null? lst)
'()
(append (reverse-list (cdr lst)) (list (car lst)))))
(define digits (digit-list n))
(equal? digits (reverse-list digits)))
 
(define (perfect-square? n)
(if (rational? (sqrt n))
(= n (expt (floor (sqrt n)) 2))
false))
 
(define (reverse-number n)
(string->number (string-reverse (number->string n))))
 
(define (find-rare-numbers count)
(define rare-numbers '())
(define i 1)
(define (is-rare? n)
(and (not (is-palindrome n))
(let* ((r (reverse-number n))
(sum (+ n r))
(diff (- n r)))
(and (perfect-square? sum)
(perfect-square? diff)))))
 
(define start-time (current-inexact-milliseconds))
(while (< (length rare-numbers) count)
(cond [(is-rare? i)
(displayln (format "Number: ~a | Elapsed time: ~a ms" i (round (- (current-inexact-milliseconds) start-time))))
(set! rare-numbers (cons i rare-numbers))])
(set! i (+ i 1)))
(reverse rare-numbers))
 
(displayln "The first 5 rare numbers are:")
(for-each (λ (x) (display x) (display "\n")) (find-rare-numbers 5))
</syntaxhighlight>
 
=={{header|Raku}}==
===Translation of Rust===
{{trans|Rust}}
<syntaxhighlight lang="raku" perl6line># 20220315 Raku programming solution
 
sub rare (\target where ( target > 0 and target ~~ Int )) {
Line 4,700 ⟶ 5,017:
my $N = 5;
say "The first $N rare numbers are,";
rare $N;</langsyntaxhighlight>
{{Out}}
<pre>The first 5 rare numbers are,
Line 4,710 ⟶ 5,027:
===Using NativeCall with Rust===
This example will make use of a modified version of the 'advanced' routine from the Rust entry.
<langsyntaxhighlight lang="bash">~> cargo new --lib Rare && cd $_
Created library `Rare` package</langsyntaxhighlight>
Add to the stock manifest file, Cargo.toml, all required dependencies and build target,
<langsyntaxhighlight lang="bash">~/Rare> tail -5 Cargo.toml
[dependencies]
itertools = "0.10.3"
 
[lib]
crate-type = ["cdylib"]</langsyntaxhighlight>
Now replace the src/lib.rs file with the following,
 
lib.rs
<langsyntaxhighlight lang="rust">use itertools::Itertools;
use std::collections::HashMap;
 
Line 4,880 ⟶ 5,197:
 
ptr
}</langsyntaxhighlight>
The needful shared library will be available after the build command,
<langsyntaxhighlight lang="bash">~/Rare> cargo build
~/Rare> file target/debug/libRare.so
target/debug/libRare.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=4f904cce7f8e82130826bf46f93fe9fe944ab9d0, with debug_info, not stripped</langsyntaxhighlight>
Here is the main Raku program,
<syntaxhighlight lang="raku" line>
<lang perl6>
use NativeCall;
 
Line 4,898 ⟶ 5,215:
for (advanced64 $N)[^$N].kv -> \nth,\rare {
printf "%d: %12d reverse %d\n", nth+1, { $_, $_.flip }(rare)
}</langsyntaxhighlight>
Output is the same.
 
Line 4,908 ⟶ 5,225:
 
These improvements made this REXX version around &nbsp; '''25%''' &nbsp; faster than the previous version &nbsp; (see the discussion page).
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays a specified amount of rare numbers. */
numeric digits 20; w= digits() + digits() % 3 /*use enough dec. digs for calculations*/
parse arg many . /*obtain optional argument from the CL.*/
Line 4,989 ⟶ 5,306:
iSqrt: parse arg x; $= 0; q= 1; do while q<=x; q=q*4; end
do while q>1; q=q%4; _= x-$-q; $= $%2; if _>=0 then do; x=_; $=$+q; end
end /*while q>1*/; return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 8 </tt>}}
<pre>
Line 5,003 ⟶ 5,320:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 5,033 ⟶ 5,350:
next
see "done..." + nl
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,049 ⟶ 5,366:
{{trans|Kotlin}}
Not sure where, but there seems to be a bug that introduces false rare numbers as output beyond what is shown
<langsyntaxhighlight lang="ruby">Term = Struct.new(:coeff, :ix1, :ix2) do
end
 
Line 5,265 ⟶ 5,582:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre> R/N 1: (65)
Line 5,291 ⟶ 5,608:
=={{header|Rust}}==
A naive and an advanced version based on Nigel Galloway
<langsyntaxhighlight lang="rust">
use itertools::Itertools;
use std::collections::HashMap;
Line 5,627 ⟶ 5,944:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,730 ⟶ 6,047:
===Traditional===
{{trans|C#}} via {{trans|Go}} Surprisingly slow, I expected performance to be a little slower than C#, but this is quite a bit slower. This vb.net version takes 1 2/3 minutes to do what the C# version can do in 2/3 of a minute.
<langsyntaxhighlight lang="vbnet">Imports System.Console
Imports DT = System.DateTime
Imports Lsb = System.Collections.Generic.List(Of SByte)
Line 5,856 ⟶ 6,173:
If System.Diagnostics.Debugger.IsAttached Then ReadKey()
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre style="height:64ex;overflow:scroll"> digs elapsed(ms) R/N Rare Numbers
Line 5,930 ⟶ 6,247:
 
Performance is better, only about 4% slower than '''C#'''.
<langsyntaxhighlight lang="vbnet">Imports System.Math
Imports System.Console
Imports llst = System.Collections.Generic.List(Of Integer())
Line 6,092 ⟶ 6,409:
nd -= 1 : Return If(f \ CULng(p(nd)) <> r Mod 10, False, (If(nd < 1, True, IsRev(nd, f Mod CULng(p(nd)), r \ 10UL)))) : End Function
#End Region
End Module</langsyntaxhighlight>
Results on the core i7-7700 @ 3.6Ghz.
<pre style="height:64ex;overflow:scroll">nth forward rt.sum rt.dif digs block time total time
Line 6,189 ⟶ 6,506:
===Traditional===
About 9.5 minutes to find the first 25 rare numbers.
<langsyntaxhighlight ecmascriptlang="wren">import "./sort" for Sort
import "./fmt" for Fmt
 
class Term {
Line 6,387 ⟶ 6,704:
Fmt.print(" $2d: $,21d", i+1, rare)
i = i + 1
}</langsyntaxhighlight>
 
{{out}}
Line 6,463 ⟶ 6,780:
===Turbo===
Ruffles the feathers a little with a time 5 times quicker than the 'traditional' version.
<langsyntaxhighlight ecmascriptlang="wren">import "./sort" for Sort
import "./fmt" for Fmt
import "./date" for Date
 
class Z2 {
Line 6,707 ⟶ 7,024:
Fmt.print(" $2d: $s $s", nd, fbTime, ftTime)
bStart = System.clock // restart block timing
}</langsyntaxhighlight>
 
{{out}}
885

edits