base3equilibree.py

Created by nicolas-patrois

Created on December 15, 2018

382 Bytes

Décompose un nombre en base 3 où les chiffres sont 1, 0 et −1 (noté T). Comme 100=3^4+3^3-3^2+3^0, on note 100=11T01 en base 3 équilibrée.


def base3eq(n):
  if n==0:
    return "0"
  if n<0:
    n*=-1
    rev=-1
  elif n>0:
    rev=1
  ch=""
  i=1
  while n:
    r=n%(i*3)//i
    if r==2:
      r=-1
    ch={1:"+",0:"0",-1:"-"}[r]+ch
    n-=r*i
    i*=3
  ch="+"+ch[1:]
  if rev==1:
    ch=ch.replace("+","1").replace("-","T")
  elif rev==-1:
    ch=ch.replace("+","T").replace("-","1")
  return ch

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.