Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Shift right by half a trit

Shift right by half a trit

This is inspired by Shift right by half a bit, but it's a little different.

Motivation

I was wondering if there is a function f that maps the non-negative integers to the non-negative integers, with the following properties:

  • It is non-decreasing (if a < b, then f(a) ≤ f(b))
  • For any non-negative integer a, f(f(a)) = floor(a/3)

It turns out there is exactly one f that satisfies these properties. Your task is to implement it.

Task

Write a program or function that takes a non-negative integer n, and applies these rules:

  • If n=0, return 0.
  • Otherwise, write n in ternary. If it starts with a 1, change the leading 1 to a 2, then remove the final digit and return the resulting number.
  • If n starts with a 2, change it to a 1 and return the resulting number.

Note that you don't need to implement this exact procedure, but I included it to give an explicit description of f.

Rules

Numbers can be represented in any reasonable format, but if you represent them as a string or list of digits, it must be in decimal or unary. I include this to specifically disallow ternary, since that skips a large part of the problem.

This is , so fewest bytes wins.

Test cases

0 -> 0
1 -> 0
2 -> 1
26 -> 17
27 -> 18
53 -> 26
54 -> 27
1337 -> 688

Answer*

Draft saved
Draft discarded
Cancel
4
  • \$\begingroup\$ -1--I've sure wanted that NAND too, but the beauty of this particular program is you've got some other ways to throw around "inversions"! \$\endgroup\$ Commented Oct 2, 2024 at 3:43
  • 1
    \$\begingroup\$ Thanks @UnrelatedString, good call. I went searching for eights but only came up with other nines. \$\endgroup\$ Commented Oct 4, 2024 at 23:44
  • 1
    \$\begingroup\$ The second one is probably more efficient because it constructs fewer lists. The first one maps 3ḍ over the first list to make a new second list before summing; the second constructs one filtered list then immediately takes its length. \$\endgroup\$ Commented Oct 5, 2024 at 18:12
  • 1
    \$\begingroup\$ That makes sense, much more overhead than the repeated divisibility counting. \$\endgroup\$ Commented Oct 6, 2024 at 1:27

AltStyle によって変換されたページ (->オリジナル) /