# Magnanimous numbers

Given an positive integer as input determine if it is a magnanimous number.

A magnanimous number is a number such that any insertion of a + sign between any two digits in base 10 results in an expression of a prime integer.

For example 40427 is magnanimous because

4+0427  = 431  is prime
40+427  = 467  is prime
404+27  = 431  is prime
4042+7  = 4049 is prime


## Output

You should output two distinct values, one when the input is magnanimous and one when the input is not.

## Scoring

The goal of this contest will be to make the size of the source code written to solve this task, given in bytes, as small as possible.

## Test Cases

1       -> True
2       -> True
4       -> True
10      -> False
98      -> True
101     -> True
109     -> False
819     -> False
4063    -> True
40427   -> True
2000221 -> True


OEIS 253996

• I'm just confused by the definition of the challenge how 1 and 2 are even valid inputs. Let alone the fact that 1 with a plus sign inserted between any two characters (no inserting) can only result in 1, which itself is not prime. – Magic Octopus Urn Jun 27 '17 at 15:30
• @MagicOctopusUrn The plus must be inserted between two digits, thus since 1 and 2 don't have two digits the set of expressions is empty. All of the members of the empty set are prime. In addition none of them are, but thats besides the point. It is a bit confusing, I'll give you that but I think it makes more sense than the alternatives. – Wheat Wizard Jun 27 '17 at 15:32

# 05AB1E, 10 bytes

### Code

η¨¹.s¨R+pP


Uses the 05AB1E encoding. Try it online! or Verify all test cases!

### Explanation

η¨             # Take the prefixes of the input and remove the last element
¹.s¨         # Take the suffixes of the input and remove the last element
R        # Reverse the array of suffixes
p      # Check if each element is prime
P     # Product of the array

• How does it work for 1 - 9. The product of an empty set is 1? Why? – Magic Octopus Urn Jun 27 '17 at 15:37
• @MagicOctopusUrn Empty product always equals 1. – Adnan Jun 27 '17 at 15:39
• @MagicOctopusUrn Taking the product is basically starting with 1 and multiplying it by each item in the set, so... – ETHproductions Jun 27 '17 at 15:39
• Ah, mathematically makes sense. Guess just like how sum on [] is equivalent to 0, using the induction property when implementing was pretty smart. – Magic Octopus Urn Jun 27 '17 at 15:42
• @jontro Yes, in UTF-8, it is 14 bytes. However, 05AB1E uses the 05AB1E code page, where this is 10 bytes. – Adnan Jun 27 '17 at 22:18

# C (gcc), 83 848583848675111 bytes

All optimizations turned off and only on GCC 32-bit.

-1 byte thanks to @ceilingcat

+some bytes for 1 case.

+some bytes for reusable functions.

i,j,r,s;f(a){for(i=10,r=1;a/i;i*=10)for(s=a%i+a/i,r*=s-1,j=2;j<s;)r*=s%j++>0;a=!r;}


Takes input as an integer. Return 1 for false cases, 0 for true cases.

Try it online!

See my another answer for Mathematica code (55 bytes).

• This should be two separate answers. Also, the Mathematica solution gives incorrect results for 1, 98, and 4063. – ngenisis Jun 28 '17 at 22:11

## Retina, 38 bytes

\B
$$*_$'$*_
S\d
G^_$|^(__+)\1+$
^$ Try it online! Prints 1 for magnanimous numbers and 0 otherwise. ### Explanation \B$$*_$'$*_  We start by matching each position between two digits (positions that aren't word boundaries) and inserting both the prefix and the suffix of that match in unary, using _ as the unary digit. So instead of inserting +s, we directly insert the unary result of the sum there. S\d  Now we split the string around digits, so that each sum goes on its own line and we get rid of those digits (there'll be an empty leading and trailing line as well, but that's not important). G^_$|^(__+)\1+$ This is the standard regex to match non-prime numbers in unary. Using a Grep stage here means that we simply keep all lines that contain positive non-primes (discarding the empty lines). ^$


Finally we check whether the string is empty. If the input was magnanimous, the previous stage will have discarded all lines (because they were all primes), and this gives us 1. Otherwise, if any line wasn't a prime, it will remain in the string and the regex fails, giving 0.

# Python 2, 8279 78 bytes

f=lambda n,d=10:n<d or d/n<all((n/d+n%d)%k*f(n,10*d)for k in range(2,n/d+n%d))


This is slow and can only cope with the test cases with memoization.

Try it online!

### Alternate version, 79 bytes

f=lambda n,d=10:n<d or f(n,10*d)>d/n<all((n/d+n%d)%k for k in range(2,n/d+n%d))


Sped up at the cost of one byte.

Try it online!

# Jelly, 12 bytes

DJ⁵*⁸dṖS€ÆPẠ


Try it online!

Verify all test cases.

• Clever use of d! – Erik the Outgolfer Jun 27 '17 at 15:23
• @EriktheOutgolfer it's the third alternative I tried, after "all partition -> filter for length 2" and "J, untruth, partition each" – Leaky Nun Jun 27 '17 at 15:24

# Java 8, 17517194 88 bytes

n->{long d=10,r=0,i,t;for(;d<=n;d*=10,r|=t-i)for(t=n/d+n%d,i=1;t%++i%t>0;);return r==0;}


-77 thanks to @PeterTaylor by using an arithmetic (instead of String with .substring) and getting rid of the separate method to check if the integer is a prime.
-6 bytes using @SaraJ's prime-checking method, so make sure to upvote her!

Try it here.

Explanation:

n->{                  // Method with long as both parameter and return-type
long d=10,r=0,i,t;  //  Some temp longs
for(;d<=n           //  Loop as long as d is below or equal to input n
//  (inclusive instead of exclusive due to special case 10)
;               //    After every iteration:
d*=10,         //     Multiple d by 10
r|=t-i)        //     and Bitwise-OR r with t-i
for(t=n/d+n%d,    //   Set t to n integer-divided by d plus n modulo-d
i=1;          //   Set i to 1
t%++i%t>0;);  //   Inner oop as long as t modulo i+1 modulo t is not 0 yet
//   (after we've first increased i by 1 with ++i)
//   (if t equals i afterwards, it means t is a prime)
return r==0;}       //  Return if r is still 0

• I think there are at least two ways to shorten this: firstly, replace the loop in p with recursion; secondly, accumulate the results such that the main function only requires one return statement by making the sentinel value from p be -1 and using & to check that all the returned values are -1. – Peter Taylor Jun 28 '17 at 8:33
• Actually, the big one is: don't use strings. – Peter Taylor Jun 28 '17 at 8:51
• n->{for(long d=10,m=1;d<n;d*=10)m|=p(n/d+n%d,2)-2;return m>0;}long p(long n,int i){return i<n?p(n%i<1?1:n,i+1):n;} – Peter Taylor Jun 28 '17 at 9:03
• @PeterTaylor Thanks for the suggestions! As for your suggested function at the end, are you sure it's correct? I currently gives incorrect results, unless I'm doing something wrong. – Kevin Cruijssen Jun 28 '17 at 9:16
• Ok, d<=n to handle 10. Stack overflow isn't a problem (the spec doesn't give a range of input which must be handled), but can be fixed and more savings obtained by reverting to a loop and inlining. – Peter Taylor Jun 28 '17 at 9:51

# Pyth, 14 bytes

.AmP_ssMcQ]dtU


Try it online! Will display True if the number is magnanimous, False otherwise. Takes the number as a string.

Explanations

.AmP_ssMcQ]dtU

Q    # Implicit input Q
tU     # Generate the range [1, 2, ..., len(Q)-1]
m                # For each index d in the above range...
cQ]d       # Split Q at index d
sM           # Convert the two parts to integers
s             # Sum
P_              # Check it is a prime
.A                 # ...end for. Check all elements are True


# Python 2, 104 102 98 96 103 bytes

• Thanks to @Wheat Wizard for 2 bytes: made i completely anonymous since it is called only once.
• Thanks to @Hyperneutrino for 4 bytes: smarter way of obtaining the numbers from the main number instead of slicing
• @Hyperneutrino saved another 2 bytes: x-1 to just x for the prime checking rarnge.
• Fixed failure for case x=10,thus adding 7 Bytes, thanks to @Dennis and @Wheat Wizard for spotting it: my earlier version was considering 1 a prime
lambda x:all((lambda x:x>1and all(x%j for j in range(2,x)))(x/10**j+x%10**j)for j in range(1,len(x)))


Try it online!

• 98 bytes – HyperNeutrino Jun 27 '17 at 15:51
• Cool, thanks @HyperNeutrino – officialaimm Jun 27 '17 at 15:55
• 96 bytes: You don't need the x-1 at the end of the range; range is exclusive on the right. – HyperNeutrino Jun 27 '17 at 15:58
• This fails for 10 (new test case). – Dennis Jun 27 '17 at 16:19
• This fails for 10. I also believe that 10 is the only number this fails for. – Wheat Wizard Jun 27 '17 at 16:20

# Japt, 24 16 bytes

This was pretty much a collaboration between @Shaggy, @ETHproduction, and myself.

¬£[YîU UtY]xÃÅej


Try it online!

Takes input as a string.

• Gah! Almost identical to the alternative solution I was working on! Here's the 22 bytes I had it down to so far. EDIT: Got it down to 20 bytes by combining stuff from both. – Shaggy Jun 27 '17 at 16:59
• @Shaggy Funny enough, I'm working on my edit right now...It's shockingly similar to yours: ethproductions.github.io/japt/… – Oliver Jun 27 '17 at 17:03
• Hint: x automatically converts the items in the array to numbers ;-) – ETHproductions Jun 27 '17 at 17:05
• Yup, that's where I'd go to too, @ETHproductions: 16 bytes. – Shaggy Jun 27 '17 at 17:06
• Also, XîU is genius. I think U¯X works for the same length, but still – ETHproductions Jun 27 '17 at 17:06

# Pip, 25 24 bytes

$&0N_%,_=1M$+(a^@_)M1,#a


Try it online!

### Explanation

a is the first command-line argument. 1,#a generates a Range containing numbers 1 through len(a)-1. To this, we map a lambda function:

$+(a^@_) a^@_ Split a at this index$+(    )  Fold the resulting 2-element list on +


Next, we map another lambda function, 0N_%,_=1, that tests for primality. I took it from this answer; you can read the explanation there. Finally, we fold the list on logical AND ($&). The result is 1 iff all the sums were prime, 0 if any of them weren't. Example, with input of 4063:  1,#a [1; 2; 3]$+(a^@_)M       [67; 103; 409]
0N_%,_=1M                [1; 1; 1]
$& 1  # CJam, 22 bytes r:L,({)_L<i\L>i+mp!},!  Try it online! Prints positive integer for truthy, zero for falsy. -1 thanks to a clever trick by Peter Taylor. -3 thanks to another tip by Peter Taylor. • 0&! is shorter than 1+:* – Peter Taylor Jun 27 '17 at 16:24 • @PeterTaylor Ooh that's clever...you abused the fact that ! returns a boolean and used set-intersection with the falsy value 0 so that you can do 0&! in 3 instead of 1&!!... – Erik the Outgolfer Jun 27 '17 at 16:27 • You can save a further 3 bytes by assigning the input to a variable, which simplifies the stack manipulations, and using the , filter operator instead of f. – Peter Taylor Jun 28 '17 at 7:34 • PS I don't see any abuse in using ! to convert to a Boolean: that was standard in GolfScript and is standard in CJam. And 1&!! would be incorrect: 0&! is the obvious test because the requirement is forall, not exists. – Peter Taylor Jun 28 '17 at 7:47 • @PeterTaylor That's not what I meant...:P – Erik the Outgolfer Jun 28 '17 at 8:41 # Japt, 23 bytes Takes input as a string. Dang it; beaten to the punch on a much shorter alternative I was working on. ¬£i+YÃÅe@OxXr"%+0+"'+)j  Test it • @ETHproductions, no, you were right; the original version was wrong; only checking for magnanimous primes. ¬£i+YÄÃe@OxX j – Shaggy Jun 27 '17 at 15:35 • I knew I hadn't lost my mind ;P – ETHproductions Jun 27 '17 at 15:35 • Fails on 4063 (should be true, is false). The trick here is that JS thinks a leading 0 means you want octal... – ETHproductions Jun 27 '17 at 15:43 • Hmmm ... OK, think I have an alternative - will take a few minutes to test it & golf it. – Shaggy Jun 27 '17 at 15:47 • I think this will fail now on some case that contains two 0s followed by two other digits... (40043, for example) Just add a + after the 0 to fix this. – ETHproductions Jun 27 '17 at 15:57 ## Mathematica, 75 bytes And@@Table[PrimeQ@ToExpression@StringInsert[#,"+",n],{n,2,StringLength@#}]&  Function which expects a String. PrimeQ@ToExpression@StringInsert[#,"+",n] returns whether inserting a + after the nth digit gives a prime number. Table[...,{n,2,StringLength@#}] gives the list of these values as n ranges from 2 to the length of the string. We then take And of each of the elements of that list. Conveniently, if StringLength@#<2, then Table[...] is the empty list, for which And@@{}==True # Mathematica, 55 504549505462 bytes It seems I should post it separately. +6 bytes for code length remeasured. +5 bytes thanks to ngenisis. And@@(qPrimeQ[#~Mod~q+⌊#/q⌋])@Rest@PowerRange@#&  Takes input as an integer and return regular True and False. The  in-between is unicode 0xF4A1, short for Function[,]. Code length is measured on file size (UTF-8 without BOM), comment if it is not correct. PowerRange[x] returns 1, 10, 100... no greater than x, which is introduced in Mathematica 10. # Plain English4,204341315251241 240 bytes (Re-)incorporated primality testing into Plain English's library, by moving 3,863 bytes into Plain English's library. Deleted 26 bytes of white space. Saved 64 bytes by abbreviating local variables. Saved 10 bytes by abbreviating the interface. Per RosLuP's suggestion, saved 1 byte by changing how m is initialized and incremented. To decide if a n number is g: Put 1 in a m number. Loop. Multiply the m by 10. If the m is greater than the n, say yes. Divide the n by the m giving a q quotient and a r remainder. Add the q to the r. If the r is not prime, say no. Repeat.  Ungolfed version of final code: To decide if a number is magnanimous: Put 1 in another number. Loop. Multiply the other number by 10. If the other number is greater than the number, say yes. Divide the number by the other number giving a quotient and a remainder. Add the quotient to the remainder. If the remainder is not prime, say no. Repeat.  Notes: The Plain English IDE is available at github.com/Folds/english. The IDE runs on Windows. It compiles to 32-bit x86 code. The Osmosian Order's dynamic fork of Plain English already had primality testing in version 4700, but it used a very inefficient algorithm (as of January through June 2017). Versions 4001-4011 of the GitHub site's dynamic fork omitted primality testing. Version 4013 of the GitHub site's dynamic fork includes primality testing. The code to perform the primality testing was developed as part of previous revisions of this answer. # Perl 6, 58 bytes {?(10,10* *...^*>$_).map({$_ div$^a+$_%$^a}).all.is-prime}


Try it online!

10, 10 * * ...^ * > $_ is the geometric sequence of multiples of ten, taken until one before the element that exceeds the input parameter $_. Then we just check that for each power of ten, the sum of the input parameter taken div and mod that power is prime.

p x=[x]==[i|i<-[2..x],xmodi<1]
i!x|i<1=0<1|0<1=p(uncurry(+)$divMod x$10^i)&&(i-1)!x
f x=(length(show x)-1)!x


Ungolfed with explanation:

-- Check if x is a prime number
p x = [x] == [i | i<-[2..x], xmodi < 1]
-- Checks all pairs of numbers a '+' can be put in between
i ! x | i<1 = 0<1                                -- Single-digit numbers are always truthy
| 0<1 = p (uncurry (+) $divMod x$ 10^i)  -- Does x split at i digits from right sum up to a prime?
&& (i-1) ! x                          -- If so, check next pair
-- Start (!) with the number of digits in x minus one
f x = (length (show x)-1) ! x

• If you use p x=[x]==[i|i<-[2..x],xmodi<1] as your prime check you can save 2 bytes. – Wheat Wizard Jun 27 '17 at 22:38
• You can also use divMod x$10^i instead of xdivMod(10^i) – Wheat Wizard Jun 27 '17 at 22:42 • @WheatWizard: I knew the prime test could still be improved somehow. ;) Thanks! – siracusa Jun 28 '17 at 3:51 # Axiom, 88 bytes f(n:PI):Boolean==(i:=10;repeat(q:=n quo i;q=0 or ~prime?(q+n rem i)=>break;i:=i*10);q=0)  test and results (10) -> [[i,f(i)] for i in [1,2,4,10,98,101,109,819,4063,40427,2000221,999999999999999999999999999999999999999999999]] (10) [[1,true], [2,true], [4,true], [10,false], [98,true], [101,true], [109,false], [819,false], [4063,true], [40427,true], [2000221,true], [999999999999999999999999999999999999999999999 ,false]]  # Brachylog, 11 bytes {~cĊℕᵐ+}ᶠṗᵐ  Try it online! { }ᶠ Find every + sum of Ċ two ℕᵐ whole numbers ~c which concatenate to the input, ᵐ and assert that all of them ṗ are prime.  # Perl 6, 35 bytes {m:ex/^(.+)(.+)$/.all.sum.is-prime}


Try it online!

### Explanation:

{                                 }     # Anonymous code block that
m:ex/^        $/ # Match all (.+)(.+) # Splits of the input number .all # Are all of them .sum # When summed .is-prime # Prime?  # Stacked, 51 bytes [tostr:#'1-~>splitat tr['+',' '##~prime]map 1,all]  Try it online! This is a function. It works by converting its argument to a string (tostr), duplicating it and obtaining its length (:#'), subtracting 1 (1-), making a range from 1 to that number (~>). The stack looks something like this, for input 40427: ('40427' (1 2 3 4))  We perform vectorized splitat, resulting in the following array to be at the top of the stack: (('4' '40' '404' '4042') ('0427' '427' '27' '7'))  Transposing this with tr, we get: (('4' '0427') ('40' '427') ('404' '27') ('4042' '7'))  Then, we map the function ['+',' '##~prime](withmap). This function does: ['+',' '##~prime] '+', concatenate a plus sign (string) ('4' '0427' '+') ' '# join by spaces '4 0427 +' #~ evaluate 431 prime check primality 1  Then, after the map, we concatenate 1. This is since all returns undef for an empty list. ## JavaScript (ES6), 70 bytes P=(n,x=2)=>n%x?P(n,x+1):n==x f=(n,i=10)=>i>n||P((n/i|0)+n%i)&f(n,i*10)  Fails on the last case in my browser due to a "too much recursion" error while calculating P(200023). Hopefully this doesn't invalidate it. # QBIC, 38 bytes _L;|[a-1|q=q*µ!_sA,b|!+!_sA,b+1,a|!}?q  ## Explanation _L | Create a variable a and set it to the length of ; the input string (A$)
[a-1|    FOR b = 1 to a-1
q=q*     multiply q by
µ       -1 if prime, 0 if not, of
!        a cast of
_s       a substring of
A,       A$b from index 1 to index b (only one index is given, so that is assumed to be the req. length from 1) |! to number + plus ! a cast of _s a substring of A, A$
b+1        from index b+1
,a         for the length of a (does not error if it exceeds the end of the string)
|!   to number
}       NEXT
?q      PRINT q, which is eitrher -1 or 1 for all-prime sums, or 0 otherwise


## CJam (21 bytes)

r:R,({RiA@)#md+mp!},!


### Dissection

r:R       e# Take a token of input and assign it to R
,(        e# Take the length of R minus one
{         e# Filter i = 0 to (length of R minus two)
Ri      e#   Push R as an integer value
A@)#    e#   Push 10 to the power of (i + 1)
md      e#   divmod
+mp!    e#   Add, primality test, negate result
},        e# The result of the filter is a list of splits which give a non-prime
!         e# Negate result, giving 0 for false and 1 for true


# Pyth, 15 14 bytes

.AmP_svcz]dtUz


Test suite

Saved a byte using Pyth's newest change.

# APL(NARS), chars 35, bytes 70

{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}


test:

  f←{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}
f¨1 2 4 10 98 101 109 819 4063 40427 2000221
1 1 1 0 1 1 0 0 1 1 1


This would be the translation in APL from Axiom post algo here...

{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}
0≥k←¯1+≢⍕⍵:1⋄  assign to k the length as array of argument return 1 if that is <=0
∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k
m←10*⍳k  m is the array pow(10,1..k)
⌊⍵÷m       the array of quotient of argumet with m
+           sum
(m∣⍵)            with array of remander
0π                 build the binary array of "are prime each"
∧/                   and that array


for(;++$k<strlen($a=$argn);$x+=$i==1)for($i=$n=substr($a,$k)+$b.=$a[$k-1];--$i&&$n%$i;);echo$x+2>$k;  prints 1 if input is magnanimous, empty output if not. Run as pipe with -nR or try it online. # Perl 5-p, 42 bytes $\=1;s//map$\&&=($+$')%$_,2..$+$'-1/ge}{
`

Try it online!