Magnanimous numbers

From Rosetta Code
Magnanimous numbers is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.


E.G.
  • 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime.
  • 3538 is not a magnanimous number. 3 + 538 == 541 which is prime; 35 + 38 == 73 which is prime; but 353 + 8 == 361 which is not prime.


Traditionally the single digit numbers 0 through 9 are included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, 1001 -> 1 + 001 (prime), 10 + 01 (prime) 100 + 1 (prime).

There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above 97393713331910, the largest one known.


Task
  • Write a routine (procedure, function, whatever) to find magnanimous numbers.
  • Use that function to find and display, here on this page the first 45 magnanimous numbers.
  • Use that function to find and display, here on this page the 241st through 250th magnanimous numbers.
  • Stretch: Use that function to find and display, here on this page the 391st through 400th magnanimous numbers


See also


C[edit]

Translation of: Go
#include <stdio.h> 
#include <string.h>
 
typedef int bool;
typedef unsigned long long ull;
 
#define TRUE 1
#define FALSE 0
 
/* OK for 'small' numbers. */
bool is_prime(ull n) {
ull d;
if (n < 2) return FALSE;
if (!(n % 2)) return n == 2;
if (!(n % 3)) return n == 3;
d = 5;
while (d * d <= n) {
if (!(n % d)) return FALSE;
d += 2;
if (!(n % d)) return FALSE;
d += 4;
}
return TRUE;
}
 
void ord(char *res, int n) {
char suffix[3];
int m = n % 100;
if (m >= 4 && m <= 20) {
sprintf(res,"%dth", n);
return;
}
switch(m % 10) {
case 1:
strcpy(suffix, "st");
break;
case 2:
strcpy(suffix, "nd");
break;
case 3:
strcpy(suffix, "rd");
break;
default:
strcpy(suffix, "th");
break;
}
sprintf(res, "%d%s", n, suffix);
}
 
bool is_magnanimous(ull n) {
ull p, q, r;
if (n < 10) return TRUE;
for (p = 10; ; p *= 10) {
q = n / p;
r = n % p;
if (!is_prime(q + r)) return FALSE;
if (q < 10) break;
}
return TRUE;
}
 
void list_mags(int from, int thru, int digs, int per_line) {
ull i = 0;
int c = 0;
char res1[13], res2[13];
if (from < 2) {
printf("\nFirst %d magnanimous numbers:\n", thru);
} else {
ord(res1, from);
ord(res2, thru);
printf("\n%s through %s magnanimous numbers:\n", res1, res2);
}
for ( ; c < thru; ++i) {
if (is_magnanimous(i)) {
if (++c >= from) {
printf("%*llu ", digs, i);
if (!(c % per_line)) printf("\n");
}
}
}
}
 
int main() {
list_mags(1, 45, 3, 15);
list_mags(241, 250, 1, 10);
list_mags(391, 400, 1, 10);
return 0;
}
Output:
First 45 magnanimous numbers:
  0   1   2   3   4   5   6   7   8   9  11  12  14  16  20 
 21  23  25  29  30  32  34  38  41  43  47  49  50  52  56 
 58  61  65  67  70  74  76  83  85  89  92  94  98 101 110 

241st through 250th magnanimous numbers:
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407 

391st through 400th magnanimous numbers:
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081 

F#[edit]

The function[edit]

This task uses Extensible Prime Generator (F#)

 
// Generate Magnanimous numbers. Nigel Galloway: March 20th., 2020
let rec fN n g = match (g/n,g%n) with
(0,_) -> true
|(α,β) when isPrime (α+β) -> fN (n*10) g
|_ -> false
let Magnanimous = let Magnanimous = fN 10 in seq{yield! {0..9}; yield! Seq.initInfinite id |> Seq.skip 10 |> Seq.filter Magnanimous}
 

The Tasks[edit]

First 45
 
Magnanimous |> Seq.take 45 |> Seq.iter (printf "%d "); printfn ""
 
Output:
0 1 2 3 4 5 6 7 8 9 11 12 14 16 20 21 23 25 29 30 32 34 38 41 43 47 49 50 52 56 58 61 65 67 70 74 76 83 85 89 92 94 98 101 110
Magnanimous[241] to Magnanimous[250]
 
Magnanimous |> Seq.skip 240 |> Seq.take 10 |> Seq.iter (printf "%d "); printfn "";;
 
Output:
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407
Magnanimous[391] to Magnanimous[400]
 
Magnanimous |> Seq.skip 390 |> Seq.take 10 |> Seq.iter (printf "%d "); printfn "";;
 
Output:
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081

Factor[edit]

Translation of: Julia
Works with: Factor version 0.99 2020-01-23
USING: grouping io kernel lists lists.lazy math math.functions
math.primes math.ranges prettyprint sequences ;
 
: magnanimous? ( n -- ? )
dup 10 < [ drop t ] [
dup log10 >integer [1,b] [ 10^ /mod + prime? not ] with
find nip >boolean not
] if ;
 
: magnanimous ( n -- seq )
0 lfrom [ magnanimous? ] lfilter ltake list>array ;
 
: show ( seq from to -- ) rot subseq 15 group simple-table. nl ;
 
400 magnanimous
[ "First 45 magnanimous numbers" print 0 45 show ]
[ "241st through 250th magnanimous numbers" print 240 250 show ]
[ "391st through 400th magnanimous numbers" print 390 400 show ]
tri
Output:
First 45 magnanimous numbers
0  1  2  3  4  5  6  7  8  9  11 12 14 16  20
21 23 25 29 30 32 34 38 41 43 47 49 50 52  56
58 61 65 67 70 74 76 83 85 89 92 94 98 101 110

241st through 250th magnanimous numbers
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407

391st through 400th magnanimous numbers
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081

Go[edit]

package main
 
import "fmt"
 
// OK for 'small' numbers.
func isPrime(n uint64) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint64(5)
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
 
func ord(n int) string {
m := n % 100
if m >= 4 && m <= 20 {
return fmt.Sprintf("%dth", n)
}
m %= 10
suffix := "th"
if m < 4 {
switch m {
case 1:
suffix = "st"
case 2:
suffix = "nd"
case 3:
suffix = "rd"
}
}
return fmt.Sprintf("%d%s", n, suffix)
}
 
func isMagnanimous(n uint64) bool {
if n < 10 {
return true
}
for p := uint64(10); ; p *= 10 {
q := n / p
r := n % p
if !isPrime(q + r) {
return false
}
if q < 10 {
break
}
}
return true
}
 
func listMags(from, thru, digs, perLine int) {
if from < 2 {
fmt.Println("\nFirst", thru, "magnanimous numbers:")
} else {
fmt.Printf("\n%s through %s magnanimous numbers:\n", ord(from), ord(thru))
}
for i, c := uint64(0), 0; c < thru; i++ {
if isMagnanimous(i) {
c++
if c >= from {
fmt.Printf("%*d ", digs, i)
if c%perLine == 0 {
fmt.Println()
}
}
}
}
}
 
func main() {
listMags(1, 45, 3, 15)
listMags(241, 250, 1, 10)
listMags(391, 400, 1, 10)
}
Output:
First 45 magnanimous numbers:
  0   1   2   3   4   5   6   7   8   9  11  12  14  16  20 
 21  23  25  29  30  32  34  38  41  43  47  49  50  52  56 
 58  61  65  67  70  74  76  83  85  89  92  94  98 101 110 

241st through 250th magnanimous numbers:
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407 

391st through 400th magnanimous numbers:
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081 

Java[edit]

 
import java.util.ArrayList;
import java.util.List;
 
public class MagnanimousNumbers {
 
public static void main(String[] args) {
runTask("Find and display the first 45 magnanimous numbers.", 1, 45);
runTask("241st through 250th magnanimous numbers.", 241, 250);
runTask("391st through 400th magnanimous numbers.", 391, 400);
}
 
private static void runTask(String message, int startN, int endN) {
int count = 0;
List<Integer> nums = new ArrayList<>();
for ( int n = 0 ; count < endN ; n++ ) {
if ( isMagnanimous(n) ) {
nums.add(n);
count++;
}
}
System.out.printf("%s%n", message);
System.out.printf("%s%n%n", nums.subList(startN-1, endN));
}
 
private static boolean isMagnanimous(long n) {
if ( n >= 0 && n <= 9 ) {
return true;
}
long q = 11;
for ( long div = 10 ; q >= 10 ; div *= 10 ) {
q = n / div;
long r = n % div;
if ( ! isPrime(q+r) ) {
return false;
}
}
return true;
}
 
private static final int MAX = 100_000;
private static final boolean[] primes = new boolean[MAX];
private static boolean SIEVE_COMPLETE = false;
 
private static final boolean isPrimeTrivial(long test) {
if ( ! SIEVE_COMPLETE ) {
sieve();
SIEVE_COMPLETE = true;
}
return primes[(int) test];
}
 
private static final void sieve() {
// primes
for ( int i = 2 ; i < MAX ; i++ ) {
primes[i] = true;
}
for ( int i = 2 ; i < MAX ; i++ ) {
if ( primes[i] ) {
for ( int j = 2*i ; j < MAX ; j += i ) {
primes[j] = false;
}
}
}
}
 
// See http://primes.utm.edu/glossary/page.php?sort=StrongPRP
public static final boolean isPrime(long testValue) {
if ( testValue == 2 ) return true;
if ( testValue % 2 == 0 ) return false;
if ( testValue <= MAX ) return isPrimeTrivial(testValue);
long d = testValue-1;
int s = 0;
while ( d % 2 == 0 ) {
s += 1;
d /= 2;
}
if ( testValue < 1373565L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 4759123141L ) {
if ( ! aSrp(2, s, d, testValue) ) {
return false;
}
if ( ! aSrp(7, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
return true;
}
if ( testValue < 10000000000000000L ) {
if ( ! aSrp(3, s, d, testValue) ) {
return false;
}
if ( ! aSrp(24251, s, d, testValue) ) {
return false;
}
return true;
}
// Try 5 "random" primes
if ( ! aSrp(37, s, d, testValue) ) {
return false;
}
if ( ! aSrp(47, s, d, testValue) ) {
return false;
}
if ( ! aSrp(61, s, d, testValue) ) {
return false;
}
if ( ! aSrp(73, s, d, testValue) ) {
return false;
}
if ( ! aSrp(83, s, d, testValue) ) {
return false;
}
//throw new RuntimeException("ERROR isPrime: Value too large = "+testValue);
return true;
}
 
private static final boolean aSrp(int a, int s, long d, long n) {
long modPow = modPow(a, d, n);
//System.out.println("a = "+a+", s = "+s+", d = "+d+", n = "+n+", modpow = "+modPow);
if ( modPow == 1 ) {
return true;
}
int twoExpR = 1;
for ( int r = 0 ; r < s ; r++ ) {
if ( modPow(modPow, twoExpR, n) == n-1 ) {
return true;
}
twoExpR *= 2;
}
return false;
}
 
private static final long SQRT = (long) Math.sqrt(Long.MAX_VALUE);
 
public static final long modPow(long base, long exponent, long modulus) {
long result = 1;
while ( exponent > 0 ) {
if ( exponent % 2 == 1 ) {
if ( result > SQRT || base > SQRT ) {
result = multiply(result, base, modulus);
}
else {
result = (result * base) % modulus;
}
}
exponent >>= 1;
if ( base > SQRT ) {
base = multiply(base, base, modulus);
}
else {
base = (base * base) % modulus;
}
}
return result;
}
 
 
// Result is a*b % mod, without overflow.
public static final long multiply(long a, long b, long modulus) {
long x = 0;
long y = a % modulus;
long t;
while ( b > 0 ) {
if ( b % 2 == 1 ) {
t = x + y;
x = (t > modulus ? t-modulus : t);
}
t = y << 1;
y = (t > modulus ? t-modulus : t);
b >>= 1;
}
return x % modulus;
}
 
}
 
Output:
Find and display the first 45 magnanimous numbers.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 14, 16, 20, 21, 23, 25, 29, 30, 32, 34, 38, 41, 43, 47, 49, 50, 52, 56, 58, 61, 65, 67, 70, 74, 76, 83, 85, 89, 92, 94, 98, 101, 110]

241st through 250th magnanimous numbers.
[17992, 19972, 20209, 20261, 20861, 22061, 22201, 22801, 22885, 24407]

391st through 400th magnanimous numbers.
[486685, 488489, 515116, 533176, 551558, 559952, 595592, 595598, 600881, 602081]

Julia[edit]

using Primes
 
function ismagnanimous(n)
n < 10 && return true
for i in 1:ndigits(n)-1
q, r = divrem(n, 10^i)
 !isprime(q + r) && return false
end
return true
end
 
function magnanimous(N)
mvec, i = Int[], 0
while length(mvec) < N
if ismagnanimous(i)
push!(mvec, i)
end
i += 1
end
return mvec
end
 
const mag400 = magnanimous(400)
println("First 45 magnanimous numbers:\n", mag400[1:24], "\n", mag400[25:45])
println("\n241st through 250th magnanimous numbers:\n", mag400[241:250])
println("\n391st through 400th magnanimous numbers:\n", mag400[391:400])
 
Output:
First 45 magnanimous numbers:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 14, 16, 20, 21, 23, 25, 29, 30, 32, 34, 38, 41]
[43, 47, 49, 50, 52, 56, 58, 61, 65, 67, 70, 74, 76, 83, 85, 89, 92, 94, 98, 101, 110]

241st through 250th magnanimous numbers:
[17992, 19972, 20209, 20261, 20861, 22061, 22201, 22801, 22885, 24407]

391st through 400th magnanimous numbers:
[486685, 488489, 515116, 533176, 551558, 559952, 595592, 595598, 600881, 602081]


Phix[edit]

function magnanimous(integer n)
integer p = 1, r = 0
while n>=10 do
r += remainder(n,10)*p
n = floor(n/10)
if not is_prime(n+r) then return false end if
p *= 10
end while
return true
end function
 
sequence mag = {}
integer n = 0
while length(mag)<400 do
if magnanimous(n) then mag &= n end if
n += 1
end while
puts(1,"First 45 magnanimous numbers: ") pp(mag[1..45],{pp_Indent,30,pp_IntCh,false,pp_Maxlen,100})
printf(1,"magnanimous numbers[241..250]: %v\n", {mag[241..250]})
printf(1,"magnanimous numbers[391..400]: %v\n", {mag[391..400]})
Output:
First 45 magnanimous numbers: {0,1,2,3,4,5,6,7,8,9,11,12,14,16,20,21,23,25,29,30,32,34,38,41,43,
                               47,49,50,52,56,58,61,65,67,70,74,76,83,85,89,92,94,98,101,110}
magnanimous numbers[241..250]: {17992,19972,20209,20261,20861,22061,22201,22801,22885,24407}
magnanimous numbers[391..400]: {486685,488489,515116,533176,551558,559952,595592,595598,600881,602081}

Raku[edit]

Works with: Rakudo version 2020.02
my @magnanimous = lazy flat ^10, (10 .. 1001).hyper.map( {
my $last;
(1 .. .chars - 1).map: -> \c { ++$last and last unless (.substr(0,c) + .substr(c)).is-prime }
next if $last;
$_
} ),
 
(1002 ..).hyper.map: {
# optimization for numbers > 1001; First and last digit can not both be even or both be odd
next if (.substr(0,1) % 2 + .substr(*-1) % 2) %% 2;
my $last;
(1 .. .chars - 1).map: -> \c { ++$last and last unless (.substr(0,c) + .substr(c)).is-prime }
next if $last;
$_
}
 
put 'First 45 magnanimous numbers';
put @magnanimous[^45]».fmt('%3d').batch(15).join: "\n";
 
put "\n241st through 250th magnanimous numbers";
put @magnanimous[240..249];
 
put "\n391st through 400th magnanimous numbers";
put @magnanimous[390..399];
Output:
First 45 magnanimous numbers
  0   1   2   3   4   5   6   7   8   9  11  12  14  16  20
 21  23  25  29  30  32  34  38  41  43  47  49  50  52  56
 58  61  65  67  70  74  76  83  85  89  92  94  98 101 110

241st through 250th magnanimous numbers
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407

391st through 400th magnanimous numbers
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081

REXX[edit]

The majority of the time consumed was in generating a list (sparse array) of suitable primes.
The genP subroutine could use a lot of optimization if wanted.
The magna function (magnanimous) was quite simple to code and pretty fast, it includes the 1st and last digit parity test.
By far, the most CPU time was in the generation of primes.

/*REXX pgm finds/displays magnanimous #s  (#s with a inserted + sign to sum to a prime).*/
parse arg bet.1 bet.2 bet.3 highP . /*obtain optional arguments from the CL*/
if bet.1=='' | bet.1=="," then bet.1= 1..45 /* " " " " " " */
if bet.2=='' | bet.2=="," then bet.2= 241..250 /* " " " " " " */
if bet.3=='' | bet.3=="," then bet.3= 391..400 /* " " " " " " */
if highP=='' | highP=="," then highP= 1000000 /* " " " " " " */
call genP /*gen primes up to highP (1 million).*/
 
do j=1 for 3 /*process three magnanimous "ranges". */
parse var bet.j LO '..' HI /*obtain the first range (if any). */
if HI=='' then HI= LO /*Just a single number? Then use LO. */
if HI==0 then iterate /*Is HI a zero? Then skip this range.*/
#= 0; $= /*#: magnanimous # cnt; $: is a list*/
do k=0 until #==HI /* [↑] traispe through the number(s). */
if \magna(k) then iterate /*Not magnanimous? Then skip this num.*/
#= # + 1 /*bump the magnanimous number count. */
if #>=LO then $= $ k /*In range► Then add number ──► $ list*/
end /*k*/
say
say center(' 'LO "──►" HI 'magnanimous numbers ', 126, "─")
say strip($)
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
magna: procedure expose @. !.; parse arg x 1 L 2 '' -1 R /*obtain #, 1st & last digit.*/
len= length(x); if len==1 then return 1 /*one digit #s are magnanimous*/
if x>1001 then if L//2 == R//2 then return 0 /*Has parity? Not magnanimous*/
do s= 1 for len-1 /*traipse thru #, inserting + */
parse var x y +(s) z; sum= y + z /*parse 2 parts of #, sum 'em.*/
if !.sum then iterate /*Is sum prime? So far so good*/
else return 0 /*Nope? Then not magnanimous.*/
end /*s*/
return 1 /*Pass all the tests, it's magnanimous.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6= 13; nP=6 /*assign low primes; # primes. */
 !.= 0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1 /*assign primality to numbers. */
do [email protected].nP+4 by 2 to highP /*only find odd primes from here on. */
if j// 3==0 then iterate /*is J divisible by #3 Then not prime*/
parse var j '' -1 _;if _==5 then iterate /*Is last digit a "5"? " " " */
if j// 7==0 then iterate /*is J divisible by 7? " " " */
if j//11==0 then iterate /* " " " " 11? " " " */
if j//13==0 then iterate /*is " " " 13? " " " */
do k=7 while k*k<=j /*divide by some generated odd primes. */
if j // @.k==0 then iterate j /*Is J divisible by P? Then not prime*/
end /*k*/ /* [↓] a prime (J) has been found. */
nP= nP+1;  !.j=1; @.nP= j /*bump P cnt; assign P to @. and  !. */
end /*j*/; return
output   when using the default inputs:
──────────────────────────────────────────────── 1 ──► 45 magnanimous numbers ────────────────────────────────────────────────
0 1 2 3 4 5 6 7 8 9 11 12 14 16 20 21 23 25 29 30 32 34 38 41 43 47 49 50 52 56 58 61 65 67 70 74 76 83 85 89 92 94 98 101 110
and took 0.00 seconds.


────────────────────────────────────────────── 241 ──► 250 magnanimous numbers ───────────────────────────────────────────────
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407
and took 0.31 seconds.


────────────────────────────────────────────── 391 ──► 400 magnanimous numbers ───────────────────────────────────────────────
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081