How many threes?

Code Golf Asked on December 21, 2020

In this task your code will be given an integer $n$ as input. Your code should then output the greatest number of multiples of $3$ that can be concatenated (in base $10$) to form $3n$ (with no leading zeros). For example if you were given $26042$ as input,


and $78126$ can be made by concatenating $78$, $12$ and $6$, so you output $3$.

Any standard forms of IO are permitted. Answers should aim to minimize the number of bytes in their code.

Here are the first $6562$ entries in this sequence starting with zero:


24 Answers

Vyxal, 6 bytes


By porting Jelly and abusing types, I managed to tie for first with 05AB1E.


3*      # multiply the input by 3
  ņ     # take cumulative sums of that number, treating it as a list
   3œ   # get the divisibility of 3 of each number and then
     ∑  # sum that list, outputting the result

Answered by Lyxal on December 21, 2020

Perl 5 -p, 32 bytes


Try it online!

Answered by Xcali on December 21, 2020

Husk, 7 bytes


Try it online!

Same as the other answer, except it uses cumulative sum.

Answered by Razetime on December 21, 2020

Jelly, 7 bytes


Try it online!

How it works

×3DÄ3ḍS  Main link. Argument: n

×3       Compute 3n.
  D      Decimal; convert 3n to the array of its digits in base 10.
   Ä     Accumulate; take the cumulative sum.
         Note that an integer and its digit sum are congruent modulo 3.
    3ḍ   Test each partial digit sum for divisibility by 3.
      S  Take the sum of the Booleans, counting the multiples of 3.

Answered by Dennis on December 21, 2020

Python 2, 48 bytes

while n:p+=n%3<1;n/=10
print p

Try it online!

Similar to ovs's answer, but takes the whole prefix mod 3 without accumulating rather than the last digit. Outputs True as 1 on input of 0.

Python 3, 42 bytes

f=lambda n:n>=1and(n%1<1/3)+f(n/10)or n==0

Try it online!

Uses ideas from ais523's very nice solution. Repeatedly floor-divides the input by 10 until it's zero, and counts how many times the fractional part is less than 1/3. On very large inputs float precision will eventually be a problem. The n=0 case is handled with or n==0 making it return True for 1. The code can work in Python 2 if the input is a float, if we rewrite n%1<1/3 as n%1*3<1 which is the same length.

Answered by xnor on December 21, 2020

Python 2, 56 bytes

while n:k+=n%10;n/=10;p+=k%3<1
print p

Try it online!

Answered by ovs on December 21, 2020

K (ngn/k), 16 bytes


Try it online!

Answered by ngn on December 21, 2020

J, 20 bytes


Try it online!

Answered by Galen Ivanov on December 21, 2020

Retina, 11 bytes of Latin-1


Try it online!

Retina works on strings rather than integers, so I'm taking the number as it'd appear in a file (digits followed by a newline).


Almost all the solutions here have a multiplication by 3, but I thought it'd be interesting to try to solve the problem without it. We already know from the algorithm most people are using that we need to identify the number of suffixes of 3n that are divisible by 3. Now, given a suffix of n (say s), 3s will appear as a suffix of 3n if the multiplication s×3 does not carry into the digit before the suffix. Meanwhile, if the multiplication s×3 does carry, then the corresponding suffix of 3n will not be divisible by 3 (as the digital root of 3*s* is divisible by 3 – 3 divides (10-1) and we're working in base 10 – and the corresponding suffix of 3*n* will be equal to 3*s* but without a leading 1 or 2, neither of which is divisible by 3).

We do need to adjust for the possibility that 3*n* has more digits than n, thus meaning that 3*n* has an extra suffix that doesn't correspond to any suffix of n. This suffix is trivially the whole number 3*n*, and will always be divisible by 3 (for obvious reasons). Thus, if the multiplication n×3 carries, we have to add 1 to the result. We can note that if n×3 doesn't carry, it will contribute 1 to the result using a naive algorithm, whereas if it does, it won't; and thus we can do this adjustment simply by counting the "suffix that represents the whole number n" unconditionally, rather than checking for a carry. Equivalently (and slightly more tersely), we can unconditionally not count this suffix, and count some other suffix instead (the empty suffix is convenient), as it'll come to the same total.

How do we determine if a multiplication by 3 would carry? Well, if the first digit of the number is greater than 3, it must; if it's less than 3, it can't. If it's 3, whether it carries or not will depend on the next digit of the number in the same way. If the number consists entirely of 3s, the multiplication won't carry (it'll stop just short at a number consisting entirely of 9s). Thus, the algorithm we want is "count the number of proper suffixes that start with 0 or more 3s, followed by 0, 1, 2, or the end of the string; plus one extra suffix".


This algorithm ends up longer than the consensus algorithm in most languages, so I'm submitting it in Retina, a language where it turns out to be shorter than the more usual method (and a similar length to golfing languages).

v`            {Count the number of} points within the input from which you can
  .             ignore one character,
   3*           and skip past any number (including zero) of 3s,
     [012¶]     to find 0, 1, 2, or the newline at the end of the input.

The requirement to ignore one character before we start looking means that the improper suffix consisting of the whole number cannot be counted (as the suffixes that we actually look at will be the ones starting one character to the right of where Retina starts, and thus not at the first character). However, the improper suffix consisting only of the newline at the end of the number will always be counted, thus giving us the one extra suffix we need.

Answered by ais523 on December 21, 2020

Haskell, 44 bytes

g.(*3).max 1
g 0=0
g n=0^mod n 3+g(div n 10)

Try it online!

Uses Delfad0r's observation that the output is the number of suffixes (equivalently, prefixes) of 3n that are multiples of 3. This method finds the prefixes arithmetically by repeatedly floor-dividing by 10 rather than using the string representation. The 0^ is a short arithmetic way to produce 1 if the exponent mod n 3 is zero, and produce 0 otherwise.

The first line is the main function, which triples the input before passing it to the helper function g which is defined recursively. The max 1 is a hack to make f(0) equal 1, since we're required to handle zero like the string '0' rather than the empty string.

Answered by xnor on December 21, 2020

Java 10, 66 bytes

n->{int m=1,r=n<1?1:0;for(n*=3;m<n;m*=10)r+=n%m%3<1?1:0;return r;}

Try it online.


Uses a combination of @BMO's Husk answer (checking how many prefixex are divisible by 3) and @Arnauld's JavaScript (ES6) answer (multiplying an integer by 10 every iteration, and get the prefixes with a modulo of this integer).

n->{             // Method with integer as both parameter and return-type
  int m=1,       //  Modulo-integer, starting at 1
      r=         //  Result-integer, starting at:
        n<1?     //   If the input is the edge-case 0:
         1       //    Start it at 1
        :        //   Else:
         0;      //    Start it at 0
  for(n*=3;      //  Multiply the input by 3
      m<n;       //  Loop as long as `m` is still smaller than `n`
      m*=10)     //    After every iteration: Multiply `m` by 10
    r+=n%m       //   If `n` modulo-`m` (to get a suffix),
          %3<1?  //   is divisible by 3:
        1        //    Increase the result-sum by 1
       :         //   Else:
        0;       //    Leave the result-sum the same by adding 0
  return r;}     //  Return the result-sum

Answered by Kevin Cruijssen on December 21, 2020

Stax, 8 bytes


Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

3*      triple input
E       convert to array of decimal digits
:+      get all prefix sums
F       for each prefix sum
  3%!   is it a multiple of 3?
  +     add to running total

Run this one

Answered by recursive on December 21, 2020

Japt -x, 12 bytes

*3 s å+ ®°v3

Try it or view results for0-1000

Answered by Shaggy on December 21, 2020

Shakespeare Programming Language, 376 bytes

T.Ajax,.Page,.Act I:x.Scene I:x[Enter Ajax and Page]Ajax:Listen tothy!You be the sum ofthe sum ofyou you you!Scene V:x.Page:You be the sum ofyou the quotient betweena cat the sum ofa cat the remainder of the quotient betweenI the sum ofa big cat a cat!Ajax:You be the quotient betweenyou twice the sum ofa big big cat a cat!Be you nicer zero?If solet usscene V.Page:Open heart

Try it online!

I wonder if the 1/(1+I/3) trick is better than a control flow.

Answered by user202729 on December 21, 2020

Retina, 35 32 bytes


Try it online! Explanation:


Multiply the input by 3.


Convert each suffix to unary.


Count the multiples of three.

Answered by Neil on December 21, 2020

Husk, 9 bytes


Try it online or verify the first 2188 terms!


#(¦3d)ṫd*3  -- example: 42
        *3  -- times 3: 126
       d    -- digits: [1,2,6]
      ṫ     -- tails: [[1,2,6],[2,6],[6]]
#(   )      -- count values that are truthy when
    d       -- | undigits: [126,26,6]
  ¦3        -- | divisible by 3: [42,0,2]
            -- : 2

Answered by ბიმო on December 21, 2020

APL (Dyalog Unicode), 14 bytes


Try it online! or verify the first 1000


             ⎕ ⍝ prompt for input
           3×  ⍝ multiply by 3
        ⍎¨⍕    ⍝ convert the number to a vector of digits
      +       ⍝ take the cumulative sum
    3|         ⍝ find each term modulo 3
+/0=           ⍝ count those that equal 0

This works because a number is divisible by three if and only if the sum of its digits is divisible by three

Answered by jslip on December 21, 2020

Haskell, 51 bytes

f n=sum[1|x<-scanr(:)"0".show$3*n,read x`mod`3<1]-1

Try it online!

The key idea is the following: given a multiple of 3 (call it $3n$), the best way to write it as the juxtaposition of multiples of 3 is to start from the end (or the beginning) and select multiples of 3 greedily. For instance, if $3n=78126$, then we get (starting from the end) a $6$, then a $12$, and finally a $78$: $78|12|6$. Note that this is possible because a number is a multiple of 3 iff the sum of its digits is a multiple of 3. Also note that if we concatenate two multiples of 3, we get another multiple of 3, so $6,12|6,78|12|6$ are all multiples of 3.

Thus the answer can be found by considering the list of suffixes of $3n$ (e.g. $[78126,8126,126,26,6]$) and counting the multiples of 3.

Answered by Delfad0r on December 21, 2020

MathGolf, 15 14 bytes


Try it online!

-1 byte thanks to JoKing


3*                Multiply the input by 3
  ▒               Convert to a list of digits
   0             Push a zero and swap the top two elements
     Æ            Execute the next 5 characters for each block
      §           Concatenate
       _          Duplicate
        3÷        Check divisibility by 3 (returns 0 or 1)
                 Swap top two elements
           ;      Discard TOS (the last swap
            ]Σ    Wrap the entire stack in an array and output its sum

I don't know if this is the correct solution to the problem but it mimics the JS solution by Arnauld. If I'm incorrect, I'll try to fix it.

Answered by maxb on December 21, 2020

Pyth, 16 15 bytes


Try it online here.

lef!.E%vT3./`*3Q   Implicit: Q=eval(input())
                   Trailing Q inferred
            `*3Q   Input * 3
            `      Convert to string
          ./       Take divisions into disjoint substrings
  f                Filter the above using:
       vT            Convert each back to integer
      %  3           Mod 3
    .E               Are any non-0?
   !                 Logical NOT
le                 Take the length of the last value
                   As the substring sets are generated in order of number of 
                   substrings, the last value is guaranteed to be the longest

Answered by Sok on December 21, 2020

05AB1E, 14 12 7 6 bytes


-5 bytes creating a port of @BMO's Husk answer.
-1 byte thanks to @Nitrodon by changing suffixes to prefixes.

Try it online or verify the first 1000 items.


3*        # Multiply the (implicit) input by 3
          #  i.e. 26042 → 78126
  η       # List of prefixes
          #  i.e. 78126 → ["7","78","781","7812","78126"]
   3Ö     # Check for each if its divisible by 3
          #  i.e. ["7","78","781","7812","78126"] → [0,1,0,1,1]
     O    # And take the sum (which is implicitly output)
          #  i.e. [0,1,0,1,1] → 3

Old 12-bytes answer:


Or alternatively €gà can be éθg.

Try it online or verify the first 1000 items


3*             # Multiply the (implicit) input by 3
               #  i.e. 26042 → 78126
  .œ           # Take all possible partitions of this number
               #  i.e. 78126 → [["7","8","1","2","6"],["7","8","1","26"],["7","8","12","6"],
               #                ...,["781","26"],["7812","6"],["78126"]]
    ʒ   }      # Filter these partitions by:
     3ÖP       #  Only keep partitions where every number is divisible by 3
               #   i.e. ["7","8","1","2","6"] → [0,0,0,0,1] → 0
               #   i.e. ["78","12","6"] → [1,1,1] → 1

               #(option 1:)
         €g    # Take the length of each remaining partition
               #  i.e. [["78","12","6"],["78","126"],["7812","6"],["78126"]] → [3,2,2,1]
           à   # And take the max (which we output implicitly)
               #  i.e. [3,2,2,1] → 3

               #(option 2:)
         é     # Sort the remaining partitions by length
               #  i.e. [["78","12","6"],["78","126"],["7812","6"],["78126"]]
               #   → [["78126"],["78","126"],["7812","6"],["78","12","6"]]
          θ    # Take the last one (the longest)
               #  i.e. [["78126"],["78","126"],["7812","6"],["78","12","6"]]
               #   → ["78","12","6"]
           g   # And take its length (which we output implicitly)
               #  i.e. ["78","12","6"] → 3

Answered by Kevin Cruijssen on December 21, 2020

Perl 6 Raku, 54 28 26 bytes

-14 bytes thanks to nwellnhof!

{sum [+](.comb)X%%3}o*×3

Try it online!

This counts how many prefixes of the number times three are divisible by 3.


{                   }o*×3  # Pass the input times 3 into the code block
     [~](.comb)           # Get all the prefixes of the number
                X%%3       # Map each to whether they are divisible by 3
 sum                       # And get the sum

Answered by Jo King on December 21, 2020

Python 2, 99 88 bytes

lambda n:g(`3*n`)
g=lambda n:int(n)%3<1and 1+max([g(n[i:])for i in range(1,len(n))]+[0])

Try it online!

Answered by TFeld on December 21, 2020

JavaScript (ES6), 41 bytes


Try it online!

Answered by Arnauld on December 21, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP