g | x | w | all
Bytes Lang Time Link
010Japt180927T181117ZShaggy
005Vyxal220426T025842ZnaffetS
5343Wolfram Language Mathematica 53 43 Bytes220426T164056ZRomanp
061Desmos220426T032948ZAiden Ch
111Retina180928T032858Zais523
004Vyxal201113T060158Zlyxal
026180927T135105ZJo King
032Perl 5 p201113T054921ZXcali
007Husk201113T042250ZRazetime
007Jelly180929T051105ZDennis
048Python 2180928T225811Zxnor
056Python 2180928T204737Zovs
016K ngn/k180928T090606Zngn
014MathGolf180927T135837Zmaxb
020J180928T075642ZGalen Iv
044Haskell180927T234047Zxnor
032Retina180927T160441ZNeil
00605AB1E180927T135419ZKevin Cr
066Java 10180927T183601ZKevin Cr
008Stax180927T183045Zrecursiv
376Shakespeare Programming Language180927T170728Zuser2027
041JavaScript ES6180927T134229ZArnauld
009Husk180927T154806Zბიმო
014APL Dyalog Unicode180927T151131Zjslip
051Haskell180927T143507ZDelfad0r
015Pyth180927T135511ZSok
088Python 2180927T134342ZTFeld

Japt, 12 10 bytes

ì*3 å+ xv3

Try it or view results for0-1000

ì*3 å+ xv3  :Implicit input of digit array
ì*3         :Convert to integer, multiply by 3, and convert back
    å+      :Cumulative sums
       x    :Sum of elements that are
        v3  :  Divisible by 3

Vyxal, 5 bytes

T¦v₃∑

Try it Online!

How?

T¦v₃∑
T     # Triple the (implicit) input
 ¦    # Cumulative sum
  v₃  # Is each element divisible by three?
    ∑ # Sum

Wolfram Language (Mathematica): (53) 43 Bytes

If[#<1,1-Sign@#,Boole[3#~Mod~1<1]+#0[.1#]]&

-10 bytes from att

Pretty long, but I figured it was worth posting anyways because it was difficult enough to golf.

Try It Online


Explanation:

If[#<1, 1-Sign@#: If our input was 0, return 1.

Boole[3#~Mod~1<1]: Otherwise, check if the fractional part of 3n is less than 1, and return 1 if so.

+#0: Then, add this same expression to this total [.1#]]& but with a tenth of the input.

I also tried using the other algorithm, but I couldn't get anything below around 75 bytes with it. Probably possible to get much lower than 75 (I'm not great at golfing), but 43 certainly seems better.

Desmos, 61 bytes

f(n)=total(0^{mod(floor(3n/10^{[0...floor(log(0^n+n))]}),3)})

Essentially does the prefix trick that some of the other answers are using. Pretty straightforward, though quite interesting to implement in Desmos.

Try It On Desmos!

Try It On Desmos! - Prettified

Retina, 11 bytes of Latin-1

v`.3*[012¶]

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).

(Note: as pointed out in the comments, v`.3*[¶-2] works for 10 bytes, but I didn't come up with it myself.)

Algorithm

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 3s is divisible by 3 – 3 divides (10-1) and we're working in base 10 – and the corresponding suffix of 3n will be equal to 3s but without a leading 1 or 2, neither of which is divisible by 3).

We do need to adjust for the possibility that 3n has more digits than n, thus meaning that 3n has an extra suffix that doesn't correspond to any suffix of n. This suffix is trivially the whole number 3n, 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".

Explanation

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`.3*[012¶]
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.

Vyxal, s, 6 5 4 bytes

3*¦₃

Try it Online!

;)

Explained

3*¦₃
3*      # multiply the input by 3
  ¦     # take cumulative sums of that number, treating it as a list
   ₃    # get the divisibility of 3 of each number and then
        # the `-s` flag sums the top of the stack before outputting

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.

Explanation:

{                   }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

Perl 5 -p, 32 bytes

$_*=3;s/./$\+=!(($t+=$&)%3)/ge}{

Try it online!

Husk, 7 bytes

#¦3∫d*3

Try it online!

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

Jelly, 7 bytes

×3DÄ3ḍS

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.

Python 2, 48 bytes

n=input()*3;p=n<1
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.

Python 2, 56 bytes

n=input()*3;k=p=0
while n:k+=n%10;n/=10;p+=k%3<1
print p

Try it online!

K (ngn/k), 16 bytes

{+/~3!+\.:'$3*x}

Try it online!

MathGolf, 15 14 bytes

3*▒0\Ƨ_3÷\;]Σ

Try it online!

-1 byte thanks to JoKing

Explanation

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.

J, 20 bytes

1#.0=[:(3|".)\3":@*]

Try it online!

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.

Retina, 35 32 bytes

.+
$.(*3*
Lv$`.+
<$&*->
<(---)*>

Try it online! Explanation:

.+
$.(*3*

Multiply the input by 3.

Lv$`.+
<$&*->

Convert each suffix to unary.

<(---)*>

Count the multiples of three.

05AB1E, 14 12 7 6 bytes

3*η3ÖO

-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.

Explanation:

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:

3*.œʒ3ÖP}€gà

Or alternatively €gà can be éθg.

Try it online or verify the first 1000 items

Explanation:

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

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.

Explanation:

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

Stax, 8 bytes

αNΘ╠╠1d}

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

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.

JavaScript (ES6), 41 bytes

f=(n,i=10)=>!(n*3%i%3)+(n*3>i&&f(n,i*10))

Try it online!

Husk, 9 bytes

#o¦3dṫd*3

Try it online or verify the first 2188 terms!

Explanation

#(¦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

APL (Dyalog Unicode), 14 bytes

+/0=3|+\⍎¨⍕3×⎕

Try it online! or verify the first 1000

Explanaition

+/0=3|+\⍎¨⍕3×⎕
             ⎕ ⍝ 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

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.

Pyth, 16 15 bytes

lef!.E%vT3./`*3

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

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!