Виведіть часткові продукти


17

Якщо довге множення , після множення чисел, вам залишаються часткові продукти, у цьому виклику ви виведете ці часткові продукти.

Оскільки для мультиплікації довге, для компенсації коду потрібно буде якомога коротше.

Приклади

34, 53
102, 1700

48, 38 
384, 1440

361, 674
1444, 25270, 216600

0, 0
0

1, 8
8

Технічні умови

  • Введення / вихід може бути у будь-якому розумному форматі, наприклад, масив, розділений комами рядок (або будь-який інший роздільник, який не є цифрою), список, аргументи функції тощо.
  • Часткові продукти повинні бути в порядку зростання.
  • Якщо частковий продукт є 0, ви можете вибрати, ви хочете випустити його чи ні.

Це тому найкоротший код у байтах виграє!


Я припускаю, що числа можуть бути рядками, правда?
Mama Fun Roll

Цей тестовий випадок 0,0 значно ускладнює.
xnor

Для чого очікуваний результат 12, 102? Більшість відповідей, схоже, повертаються 24, 0, 1200.
Денніс

@Dennis 24, 0, 1200чудово. Я
вкажу

Відповіді:


4

Желе, 10 байт

DU×µLR’⁵*×

Спробуйте в Інтернеті!

Як це працює

DU×µLR’⁵*×  Left argument: multiplier -- Right argument: multiplicant

D           Convert the multiplier to base 10 (array of digits).
 U          Reverse the array.
  ×         Multiply each digit by the multiplicant.
   µ        Begin a new, monadic chain. Argument: A(array of products)
    L       Get the length of A.
     R      Turn length l into [1, ..., l].
      ’     Decrement to yield [0, ..., l-1].
       ⁵*   Compute 10**i for each i in that range.
         ×  Hook; multiply the powers of ten by the corresponding elements of A.

3
Я здогадуюсь, що назва цієї мови походить від того, що вона змушує всіх відчувати себе желе.
геокавель

7

Pyth, 12 байт

.e**Qsb^Tk_w

Тестовий набір

Приймає розділений новий рядок, наприклад,

361
674

Пояснення:

.e**Qsb^Tk_w
                Implicit: Q = eval(input()),T = 10
           w    Input the second number as a string.
          _     Reverse it.
.e              Enumerated map, where b is the character and k is the index.
     sb         Convert the character to an int.
   *Q           Multiply by Q.
  *    ^Tk      Multiply by T ^ k. (10 ^ index)

4

JavaScript (ES7), 48 байт

(a,b)=>[...b+""].reverse().map((d,i)=>10**i*a*d)

ES6 (56 байт)

(a,b)=>[...b+""].reverse().map((d,i)=>a*d+"0".repeat(i))

Пояснення

Повертає масив часткових продуктів у вигляді чисел.

(a,b)=>
  [...b+""]    // convert the multiplier to an array of digits
  .reverse()   // reverse the digits of the multiplier so the output is in the right order
  .map((d,i)=> // for each digit d of the multiplier
    10**i      // get the power of ten of the digit
      *a*d     // raise the product of the digit to it
  )

Тест

Тест використовує Math.powзамість того, **щоб він працював у стандартних браузерах.



3

APL, 21 байт

{⍺×x×10*1-⍨⍳≢x←⊖⍎¨⍕⍵}

Це діадійна функція, яка приймає цілі числа зліва та справа та повертає масив. Щоб викликати його, призначте його змінній.

Пояснення:

             x←⊖⍎¨⍕⍵} ⍝ Define x to be the reversed digits of the right input
     10*1-⍨⍳≢         ⍝ Generate all 10^(1-i) for i from 1 to the number of digits
{⍺×x×                 ⍝ Multiply the right input by the digits and the powers of 10

1
⍎¨⍕досить розумний.
Денніс

2

05AB1E , 15 байт

Код:

VDgUSXFTNmY**=\

Пояснення:

VDgUSXFTNmY**=\

V                 # Assign the input to Y
 D                # Duplicate of input, because the stack is empty
  g               # Pushes the length of the last item
   U              # Assign the length to X
    S             # Split the last item
     X            # Pushes X (length of the last item)
      F           # Creates a for loop: for N in range(0, X)
       TNm        # Pushes 10 ^ N
          Y       # Pushes Y (first input)
           *      # Multiplies the last two items
            *     # Multiplies the last two items
             =    # Output the last item
              \   # Discard the last item

2

Pyth, 26 байт

DcGHKjHTFNJlK*G*@Kt-JN^TN

Це визначає функцію cтак, що вона приймає 2аргументи, а функція друкує часткові продукти.

DcGHKjHTFNJlK*G*@Kt-JN^TN
DCGH                      Define function c(G, H)
    KjHT                  Set K to the list of digits converting H to base 10
        FNJlK             Set J to the length of K and loop with variable N
                          (Implicit: print)
             *G*@Kt-JN    Calculates the partial product
                      ^TN Raising it to the appropriate power of 10

1

MATL , 18 байт

ij48-tn:1-P10w^**P

Компілятор (5.1.0) працює в Matlab і Octave.

Кожне число вводиться в окремий рядок.

Приклад

>> matl ij48-tn:1-P10w^**P
> 361
> 674
1444  25270 216600

Пояснення

i           % input first number (say 361)
j           % input second number, interpreted as a string (say '674')
48-         % subtract '0' to obtain vector of figures (gives [6 7 4])
tn:1-P      % vector [n-1, ... 1, 0] where n is the number of figures (gives [2 1 0])
10w^        % 10 raised to that, element-wise (gives [100 10 1])
*           % multiply, element-wise (gives [600 70 4])
*           % multiply (gives 361*[600 70 4], or [216600 25270 1444])
P           % flip vector ([1444 25270 216600]). Implicitly display

1

Haskell, 60 57 54 байт

g x=zipWith(\b->(x*10^b*).read.pure)[0..].reverse.show

На 5 байт менше (скиньте .show ), якщо я можу взяти друге число як рядок.

Приклад використання: g 361 674->[1444,25270,216600] .

Помножити кожну цифру реверсу yз xі шкалою з 10^iякоїi = 0,1,2,... .

Редагувати: Дякую @Mauris за 3 байти!


Можна навіть зробити (\b->(x*10^b*).read.pure).
Лінн

@Mauris: Приємно. Дуже дякую!
німі

1

Джулія, 50 49 байт

f(a,b)=[a*d*10^~-i for(i,d)=enumerate(digits(b))]

Це функція, яка приймає два цілих числа і повертає цілий масив.

digitsФункція повертає масив цифр в целочисленном вхідному в в зворотному порядку. Ми отримуємо індекс, пари значень за допомогоюenumerate та обчислюючи часткові добутки як перший вхідний раз, коли цифри 10 разів піднімаються до потужності індексу цифри - 1.

Збережено байт завдяки Деннісу!



1

CJam, 19 17 байт

q~W%eef{~~A@#**}p

Приймає вхід, коли перший елемент є цілим числом, а другий - рядком (наприклад 34 "53"). Пропозиції вітаються, оскільки я впевнений, що вони можуть бути коротшими. Дякуємо Деннісу за збереження двох байтів.

Спробуйте в Інтернеті.

Пояснення

q~    e# Get input and evaluate it, x and "y"
W%    e# Reverse y so it will be properly sorted
ee    e# Enumerate through y with each character and its index
f{    e# For each digit in y...
  ~~  e# Convert the digit to an integer on the stack
  A@# e# Take 10 to the power of y's index
  **  e# Multiply all three together to get the final result
}
p     e# Print the array

1
~~A@#**економить пару байт.
Денніс

1

Хаскелл, 37 байт

a%0=[]
a%b=b`mod`10*a:(a*10)%div b 10

Ніяких строфікуючих, просто арифметичних. Рекурсивно перетворює найменший частковий продукт до решти, де остання цифра bобрізається і застосовується множник 10. Пріоритет оператора працює чудово.


0

𝔼𝕊𝕄𝕚𝕟, 11 символів / 23 байти (неконкурентно)

ᴙíⓢⓜî*$*Ⅹⁿ_

Try it here (Firefox only).

Знайдено помилку під час кодування рішення цієї проблеми ...

Пояснення

          // Implicit: î = input 1, í = input 2
ᴙíⓢ      // reverse í and split it into an array
ⓜî*$*Ⅹⁿ_ // multiply î by each individual digit in í and put in previous array
          // implicit output

0

Japt , 28 байт

I=[]Vs w m@IpApY+1 /A*U*X};I

Пояснення:

I=[]Vs w m@IpApY+1 /A*U*X};I
I=[]                         //that's simple, init an array I
    Vs                       //take the second input and convert to string
       w                     //reverse it and...
         m@              }   //...map through the chars; X is a char, Y is counter
           Ip............    //push the following value into I...
             ApY+1 /A*U*X    //10^(Y+1)/10*U*X, U is the first input
                           I //output the resulting array

Через помилку в інтерпретаторі доводиться використовувати ApY+1 /10замість ApY, тому що Ap0(що становить 10 ^ 0) дає 100. Я думаю, це з тієї причини, щоб дозволити швидке квадратування з Ap, але 0не означає "відсутність аргументів". Plz fix, Eth.
nicael

0

Python 2, 42 байти

f=lambda a,b:b*[0]and[b%10*a]+f(a*10,b/10)

Ніяких строфікуючих, просто арифметичних. Рекурсивно додає найменший частковий добуток до решти, де bвкорочується остання цифра і застосовується множник 10.

Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.