title: PKCS#7 padding validation

text:
# Question
Title: PKCS#7 padding validation
In cryptography, PKCS#7 padding is a padding scheme which adds a number of bytes N ≥ 1, where the value of each added byte is equal to N.

For example, `Hello, World!`, which has 13 bytes, is the following in hex:

```
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21

```

If we choose to PKCS#7 pad to length 16, then the result is:

```
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 03 03 03

```

And if we choose to pad to length 20, then the result is:

```
48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 07 07 07 07 07 07 07

```

Note that in the first example we add three `03` bytes, and in the second we add seven `07` bytes.

Your task will be to *validate* whether a string (or integer array) has correct PKCS#7 padding. That is, if the last byte of the input string is N, then your program should check that the last N bytes of the string are equal to N.

## Input

A single nonempty ASCII string containing characters between code points 1 and 127 inclusive. If you wish, you may take input as an array of integers instead.

## Output

A truthy value if the input string has valid PKCS#7 padding, otherwise a falsy value.

Both functions and full programs are acceptable. This is , so the aim is to minimise the number of bytes in your code.

## Test cases

The integer array version of inputs is presented here — the string version would have unprintable characters for many of the following test cases:

**Truthy:**

```
[1]
[1, 1]
[2, 1]
[2, 2]
[5, 6, 5, 3, 3, 3]
[1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2]
[95, 115, 80, 32, 71, 7, 122, 49, 13, 7, 7, 7, 7, 7, 7, 7, 7]
[27, 33, 54, 65, 97, 33, 52, 55, 60, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
[15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15]

```

**Falsy:**

```
[2]
[1, 2]
[5, 5, 5, 5]
[5, 6, 5, 4, 4, 4]
[3, 3, 3, 94, 3, 3]
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 127]
[50, 39, 94, 105, 49, 29, 74, 102, 2, 106, 44, 7, 7, 7, 7, 7, 7]
[26, 27, 59, 25, 122, 110, 20, 30, 114, 6, 9, 62, 121, 42, 22, 60, 33, 12]

```

# Answer
# Python, ~~47~~ ~~34~~ 33 bytes

```
lambda s:s[-1:]*s[-1]==s[-s[-1]:]

```

`s[-1]` is the last member of the list `s`. Checks that the last `s[-1]` members of the input array `s` are the same as an array of `s[-1]` repeated that many times.

Takes input as an array of integers. This is a lambda expression; to use it, assign it by prefixing `lambda` with `f=`.

Try it on Ideone!

To test:

```
>>> f=lambda s:s[-1:]*s[-1]==s[-s[-1]:]
>>> f([27, 33, 54, 65, 97, 33, 52, 55, 60, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10])
True
>>> f([50, 39, 94, 105, 49, 29, 74, 102, 2, 106, 44, 7, 7, 7, 7, 7, 7])
False

```

*Saved 13 bytes thanks to Leaky Nun!*

*Saved a byte thanks to Dennis!*
> 8 votes

# Answer
# Brachylog, 14 bytes

```
~c[A:B]t#=h~lB

```

Try it online!

```
~c[A:B]t#=h~lB
~c[A:B]                input is concatenation of A and B
       t               B
        #=             has all equal elements
          h~lB         the first item of B is the length of B

```
> 7 votes

# Answer
# Jelly, 5 bytes

```
ŒgṪṫṪ

```

Input is an array of code points, output is a non-empty array (truthy) or an empty array (falsy).

Try it online! or verify all test cases.

### How it works

```
ŒgṪṫṪ  Main link. Argument: A (array)

Œg     Group all runs of consecutive, equal integers.
  Ṫ    Tail; yield the last run. It should consist of n or more occurrences of n.
    Ṫ  Tail; yield n, the last element of A.
   ṫ   Dyadic tail; discard everything after the n-th element of the last run.
       If the last run was long enough, this will yield a non-empty array (truthy);
       if not, the result will be an empty array (falsy).

```
> 7 votes

# Answer
# Pyth, 5 bytes

```
gFer8

```

RLE on input, take the last pair and check if the number of repeats is greater or equal than the value.

Try it online: Demonstration or Test Suite
> 7 votes

# Answer
## CJam, ~~9~~ 8 bytes

*Thanks to Sp3000 for saving 1 byte.*

```
{e`W=:/}

```

Takes an integer list as input and returns `0` (falsy) or a positive integer (truthy).

Test suite.

### Explanation

```
e`   e# Run-length encoding, yielding pairs of run-length R and value V.
W=   e# Get the last pair.
:/   e# Compute R/V, which is positive iff R ≥ V. Works, because V is guaranteed
     e# to be non-zero.

```
> 6 votes

# Answer
# 05AB1E, 9 bytes

No run-length encodings for osabie :(

```
¤sR¬£¬QOQ

```

Explanation:

```
¤           # Get the last element of the array
 s          # Swap the two top elements
  R         # Reverse the array
   ¬        # Get the first element
    £       # Substring [0:first element]
     ¬      # Get the first element
      Q     # Check if they are equal
       OQ   # Sum up and check if equal

```

With an example:

```
¤           # [5, 6, 5, 3, 3, 3]  3
 s          # 3  [5, 6, 5, 3, 3, 3]
  R         # 3  [3, 3, 3, 5, 6, 5]
   ¬        # 3  [3, 3, 3, 5, 6, 5]  3
    £       # 3  [3, 3, 3]
     ¬      # 3  [3, 3, 3]  3
      Q     # 3  [1, 1, 1]
       OQ   # 3==3 which results into 1

```

Uses the **CP-1252** encoding. Try it online!
> 6 votes

# Answer
# MATL, 10 bytes

*Thanks to @Adnan for noticing a problem with an earlier version of the code*

```
P0hG0):)&=

```

When the input has correct padding, the output is an array containing only ones, which is truthy. When it has incorrect padding, the output is an array containing at least a zero, and so is falsy.

Try it online! Or verify all test cases.

### Explanation

```
P     % Implicitly take numeric array as input. Reverse the array
0h    % Append a 0. This ensures falsy output if input array is too short
G0)   % Push input again. Get its last element
:     % Range from 1 to that
)     % Apply as index into the array
&=    % 2D array of all pairwise equality comparisons. Implicitly display

```
> 5 votes

# Answer
## Mathematica, 29 bytes

```
#&@@#<=Length@#&@*Last@*Split

```

Split the input into runs of equal elements, extract the last, and check that its first element is less than or equal to the length of that run.
> 4 votes

# Answer
## Haskell, 50 bytes

```
import Data.List
((>=)<$>head<*>length).last.group

```

Takes an array of integers as input.
> 3 votes

# Answer
# J, 13 bytes

```
#~@{:-:{:{.|.

```

Takes the list as a single argument and outputs `1` if it is truthy and `0` if falsey.

## Usage

```
   f =: #~@{:-:{:{.|.
   f 5 6 5 3 3 3
1
   f 5 6 5 4 4 4
0

```

## Explanation

```
#~@{:-:{:{.|.  Input: array A
           |.  Reverse A
       {:      Get the last value in A
         {.    Take that many values from the reverse of A
   {:          Get the last value in A
#~@            Make a list with that many copies of the last value
     -:        Test if the list of copies matches the sublist of A and return

```
> 2 votes

# Answer
# Brain-Flak, 54 bytes

```
(({})[()]){({}[()]<({}[({})]){<>}{}>)}{}{<>(<(())>)}{}

```

Input is a list of integers, output is 1 for truthy and empty for falsey.

## Explanation

```
(({})[()]){ Loop a number of times equal to the last integer in the input - 1
    ({}[()] Handle loop counter
        < Silently...
            ({}[({})]) Replace the last code point in the string with its difference with the code point before it
            {<>} If the difference is not zero then switch stacks
            {} Discard the difference
        > End silently
    ) Handle loop counter
} End loop
{} Discard the loop counter
{<>(<(())>)} If the top of the current stack is not 0 (which means we have not switched stacks push 0 then 1
{} Discard the top of the stack (either nothing if falsey or 0 if truthy)

```

The loop does not immediately end when a value that would result in a falsey return is encountered. It is instead switched to the other stack which is empty and spends the rest of its iterations comparing 0 and 0.
> 2 votes

# Answer
## Batch, 101 bytes

```
@for %%a in (%*)do @set/an=%%a,c=0
@for %%a in (%*)do @set/ac+=1,c*=!(n-%%a)
@if %c% geq %n% echo 1

```

Takes input as command-line parameters, loops over them all so that it can get the last one into `n`, loops over them all again to count the run of trailing `n`s, finally printing `1` if the count is at least equal to `n`. Alternatively if printing `0` or a non-zero value is acceptable, then for 93 bytes, change the last line to `@cmd/cset/ac/n`.
> 1 votes

# Answer
# Haskell, 49 bytes

```
f s|x<-(==last s)=x.length.fst.span x.reverse$s

```

Try it on Ideone.

Shorter version which returns `True` for truthy and `False` or an exception for falsy:

```
((==).head>>=all).(head>>=take).reverse

```
> 1 votes

# Answer
## Javascript (ES6), ~~51~~ ~~47~~ 41 bytes

```
a=>(r=k=>a.pop()^n?k<2:r(k-1))(n=a.pop())

```

Examples:

```
let f =
a=>(r=k=>a.pop()^n?k<2:r(k-1))(n=a.pop())

console.log(f([5, 6, 5, 3, 3, 3]))
console.log(f([5, 6, 5, 4, 4, 4]))
```
> 1 votes

# Answer
# Dyalog APL, 10 bytes

```
(⊃∧.=⊃↑⊢)⌽

```

Is the first
`∧.=` all-equal to
the first
*n* taken from
the
reversed argument?

TryAPL online!
> 1 votes

# Answer
# Brain-Flak 84 bytes

*100000000 beat me here*

Try It Online!

```
((({}))){({}[()]<(({})<([{}]{}<>)<>>)>)}<>([])({<{}>{}<([])>}{}<(())>){((<{}{}>))}{}

```

Takes input as array of integers.

Explanation to come.

Here is a 64 byte version that outputs the not of the answer:

```
((({}))){({}[()]<(({})<([{}]{}<>)<>>)>)}<>([])({<{}>{}<([])>}{})

```
> 1 votes

# Answer
# C 91 Bytes

```
int f(int*l){int n;for(n=0;l[++n];);l+=n-1;for(int i=*l;i;)if(l[-i--+1]^*l||n<*l)return 0;}

```

Input: a pointer to a null-terminated array.
Output: returns `0` for invalid padding and non-zero for valid (the last element in the array)

Examples:

```
int a[] = {5, 6, 5, 3, 3, 3, 0};
printf("%d\n", f(&a[5], 6));

int b[] = {1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0};
printf("%d\n", f(&b[11],12 ));

int m[] = {5, 6, 5, 4, 4, 4, 0};
printf("%d\n", f(&m[5], 6));

int n[] = {3, 3, 3, 94, 3, 3, 0};
printf("%d\n", f(&n[5], 6));

```

Gives:

```
3
2
0
0

```

This does rely on undefined behavior. If the padding is valid there is no return statement, but using `gcc -std=c99` this returns the last element of the array that was passed in (at least on my machine).
> 1 votes

# Answer
# Perl 5, 30 bytes

Includes `+1` for `-p`

```
#!/usr/bin/perl -p
$_=/(.)\1*\z/s+length$&>ord$1

```

Try it online!
> 1 votes

# Answer
# Brachylog, 6 bytes

```
a₁=.l∈

```

Try it online!

Outputs through predicate success or failure, as Leaky Nun's Brachylog v1 answer does. Takes a similar approach, as well, but comes out a lot shorter.

```
a₁        There exists a suffix of the input
  =       the elements of which are all equal
   .      which is the output variable
    l     the length of which
     ∈    is an element of
          the output variable.

```

# Brachylog, 6 bytes

```
ḅt.l≥∈

```

Try it online!

An alternate version that comes out to the same length which takes some inspiration from Dennis' Jelly answer.

```
 t        The last
ḅ         block of consecutive equal elements of the input
  .       is the output variable
   l      the length of which
    ≥     is greater than or equal to
     ∈    an element of
          the output variable.

```
> 1 votes

# Answer
# Retina, 34 bytes

Byte count assumes ISO 8859-1 encoding.

```
.+
$*
\b(1(1)*)(?<-2>¶\1)*$(?(2)!)

```

Input is a linefeed-separated list of integers. Prints `0` or `1`.

Try it online! (The first line enables a test suite, where there is one space-separated test case per line.)

An alternative idea that ends up at 35 bytes and prints `0` or a positive integer:

```
.+
$*
\b(?=(1+)(¶\1)*$)(?<-2>1)*1\b

```
> 0 votes

# Answer
## Pyke, 7 bytes

```
eQ>}lt!

```

Try it here!
> 0 votes

# Answer
# Javascript (ES5), 89 bytes

```
function(b){for(var d=b[b.length-1],c=0;c<d;c++)if(b[b.length-c-1]!=d)return!1;return!0};

```

Ungolfed:

```
function a(arr){
var b=arr[arr.length-1];
for(var i=0;i<b;i++){
    if(arr[arr.length-i-1]!=b)return false;
}
return true;
}

```
> 0 votes

---
Tags: code-golf, string, decision-problem, cryptography
---


title: Rectangular difference

text:
# Question
Title: Rectangular difference
In this challenge, you are given two overlapping rectangles, and you need to calculate the rectangles created by removing one from the other.

For example, if you remove the red rectangle from the black one:

You end up with one of the following two rectangle sets:

You'll also need to handle the following:

To be more explicit:

* You will input the coordinates of two rectangles, A and B.
* You need to output the fewest non-overlapping rectangles that cover all of the area of A without B. Any possible covering is allowed
* Rectangular coordinates are passed as 4 integers. You can pass them in two pairs (representing the two corner points), or as a tuple/list of 4 integers. Your inputs and outputs need to be consistent.
* A and B will not necessarily overlap or touch, and each will have an area of at least 1

# Test cases:

```
[(0 0) (5 5)] [(3 4) (8 7)]   -> [(0 0) (5 4)] [(0 4) (3 5)] # or [(0 0) (3 5)] [(3 0) (5 4)]
[(2 4) (10 11)] [(5 5) (6 6)]  -> [(2 4) (10 5)] [(2 5) (5 6)] [(6 5) (10 6)] [(2 6) (10 11)]    #Other sets of 4 rectangles are possible
[(3 3) (8 8)] [(0 1) (10 8)]   ->    #No rectangles should be output
[(0 0) (5 5)] [(1 1) (10 2)]   -> [(0 0) (1 5)] [(1 0) (2 1)] [(2 0) (5 5)]  #Other sets of 3 rectangles are possible
[(1 5) (7 8)] [(0 0) (1 10)]   -> [(1 5) (7 8)]  #Only possible output
[(4 1) (10 9)] [(2 5) (20 7)]   -> [(4 1) (10 5)] [(4 7) (10 9)]  #Only possible output
[(1 1) (8 8)] [(0 6) (9 9)]     -> [(1 1) (8 6)]   #Only possible output

```

This is a , so make your code as short as possible!

# Answer
# Python 2, ~~375~~ ~~360~~ ~~345~~ 343 bytes

```
from itertools import*;P=product
def f(S,M):(l,t),(r,b)=S;(L,T),(R,B)=M;u,v,x,y=(L>=r)+(l<L),(T>=b)+(t<T),(R>=r)+(l<R),(B>=b)+(t<B);return[S]if v==y!=1or u==x!=1else[list(p(p(*zip(*(S+M))),repeat=2))[[43,197,6,199,9,231,142,229,53,189,134,181][int(i,36)]]for i in '38,491,258,2058,8,4B,28,208,7,41,27,461,,4,2,4A'.split(',')[u+2*v+4*x+8*y-12]]

```

Try it online!

EDITS: -15 from suggestions from @notjagan; another -15 by re-encoding the array of solution rectangles to int36 format and a short lookup table; another -2 by replacing product with p as per @musicman.

A function that takes two rectangles, each rect being a tuple of ((left,top), (right,bottom)); returns a list of the resulting rectangles.

The basic strategy:

```
     |     |
 0,0 | 1,0 | 2,0
-----A-----+-----
     |     |
 0,1 | 1,1 | 2,1
-----+-----B-----
     |     |
 0,2 | 1,2 | 2,2
     |     |

```

In the above diagram, the points A and B are the upper left and lower right, respectively, of the 'Source' rectangle (the first rect).

We find the placement of each of the the upper left `(u,v)` and lower right `(x,y)` of the 'Mask' rectangle in that grid.

If both these points are in the first or last column; or first or last row; then there is no overlap; and we can return just the Source rect.

Otherwise, there are 16 cases remaining; for example, the OP's first example is the case we can label `(1,1),(2,2)`. Each case can be mapped to a set of resulting rectangles whose corners are always coordinates with horizontal values in either Source rectangles left,right, or the Mask rectangles left,right; and similarly for the vertical values, the Source's top,bottom or the masks.

For example, for the `(1,1),(2,2)` case, the rectangles would be `((l,t),(T,r))` and `((l,T),(R,b))`, where `l,t,r,b` and `L,T,R,B` are the left, top, right and bottom of the Source and Mask rectangles, respectively.

So we can create a lookup table that maps the coordinates to the set of all such possible combinations (which is what the `product(product(*zip(*)))` bit is about) to a set of rectangles that should be provided for each of the cases (which, after some golfy-decompression, is what the rest of the list stuff is about).
> 3 votes

# Answer
# JavaScript, 115 bytes

```
f=a=>b=>b.some((n,i)=>(a[i^2]<n)^i/2)?[a]:b.map((n,i)=>a[i&1]<n&&n<a[i|2]&&(p=[...a],p[i^2]=a[i]=n,p)).filter(x=>x)

```

overlapping version:

```
f=a=>b=>b.some((n,i)=>(a[i^2]<n)^i/2)?[a]:b.map((n,i)=>a[i&1]<n&&n<a[i|2]&&(p=[...a],p[i^2]=n,p)).filter(x=>x)

```

Input in following format: `f([1,1,8,8])([0,6,9,9])`

---

Denote input as ((x1, y1), (x2, y2)), ((x3, y3), (x4, y4))

If any one of following conditions is met, return first rectangle as is:

* x3 \> x2
* x4 \< x1
* y3 \> y2
* y4 \< y1

otherwise

* If x1 \< x3 \< x2 then we generate a rectangle ((x1, y1), (x3, y2)); and set x1 := x3
* If x1 \< x4 \< x2 then we generate a rectangle ((x4, y1), (x2, y2)); and set x2 := x4
* If y1 \< y3 \< y2 then we generate a rectangle ((x1, y1), (x2, y3)); and set y1 := y3
* If y1 \< y4 \< y2 then we generate a rectangle ((x1, y4), (x2, y2)); and set y2 := y4
> 3 votes

# Answer
# Java, 268 bytes

```
class W{public static void main(String[]z) {int a[]={0,0,0,0},i,j,y[]={0,1,4,3,6,1,2,3,4,1,6,5,4,7,6,3};for(i=0;i<4;i+=1){for(j=0;j<4;j+=1){a[j]=Integer.parseInt(z[y[i*4+j]]);}if(a[0]<a[2] && a[1]<a[3]){for(j=0;j<4;j+=1){System.out.println(String.valueOf(a[j]));}}}}}

```

Ungolfed

```
class W{
    public static void main(String[]z) {
        int a[]={0,0,0,0},i,j,y[]={0,1,4,3,6,1,2,3,4,1,6,5,4,7,6,3};

        for(i=0;i<4;i+=1){
            for(j=0;j<4;j+=1){
                a[j]=Integer.parseInt(z[y[i*4+j]]);
            }
            if(a[0]<a[2] && a[1]<a[3]){
                for(j=0;j<4;j+=1){
                    System.out.println(String.valueOf(a[j]));
                }
            }
        }
    }
}

```

Pass input as arguments. Example

```
java -jar W.jar 0 0 5 5 3 4 8 7

```
> 1 votes

# Answer
# Python 2, 272 bytes

```
lambda((a,b),(c,d)),((e,f),(g,h)):[([([[(a,b),(e,min(h,d))]]+[[(g,max(b,f)),(c,d)]]*2+[[(max(a,e),b),(c,f)]]*4+[[(a,h),(min(c,g),d)]])[m-1]for m in M&{1,2,4,8}]if M&{0}else[(a,b),(c,d)])for M in[{(x<e)*1+(x>g)*2+(y<f)*4+(y>h)*8 for x in range(a,c)for y in range(b,d)}]][0]

```

Try it online!

This works by testing every cell inside the first rectangle for leftness=1,aboveness=4,rightness=2,and belowness=8 w/r to the other, and ORing the result. If the other does not intersect=0 with the first, then the original is returned, otherwise some combination of a left slice, right slice, upper slice and lower slice is returned, with accomodation for overlap.
> 0 votes

---
Tags: code-golf, geometry, grid, set-partitions
---


# Question
Title: Write a function that takes (x, y) and return x to the power of y WITHOUT Loops
This is a really neat short challenge.

Write a function or a procedure that takes two parameters, `x` and `y` and returns the result of `x<sup>y</sup>` WITHOUT using loops, or built in power functions.

**The winner is the most creative solution, and will be chosen based on the highest number of votes after 3 days.**

# Answer
> 27 votes
## APL (7)

```
{×/⍵/⍺}

```

Left argument is base, right argument is exponent, e.g.:

```
     5 {×/⍵/⍺} 6
15625

```

Explanation:

* `⍵/⍺` replicates   times, e.g. `5 {⍵/⍺} 6` -\> `5 5 5 5 5 5`
* `×/` takes the product, e.g. `×/5 5 5 5 5 5` -\> `5×5×5×5×5×5` -\> `15625`

# Answer
> 27 votes
# C#: Floating point exponents

OK, this solution is quite fragile. You can easily break it by throwing ridiculously huge numbers like 6 at it. But it works beautifully for things like `DoublePower(1.5, 3.4)`, and doesn't use recursion!

```
    static double IntPower(double x, int y)
    {
        return Enumerable.Repeat(x, y).Aggregate((product, next) => product * next);
    }

    static double Factorial(int x)
    {
        return Enumerable.Range(1, x).Aggregate<int, double>(1.0, (factorial, next) => factorial * next);
    }

    static double Exp(double x)
    {
        return Enumerable.Range(1, 100).
            Aggregate<int, double>(1.0, (sum, next) => sum + IntPower(x, next) / Factorial(next));
    }

    static double Log(double x)
    {
        if (x > -1.0 && x < 1.0)
        {
            return Enumerable.Range(1, 100).
                Aggregate<int, double>(0.0, (sum, next) =>
                    sum + ((next % 2 == 0 ? -1.0 : 1.0) / next * IntPower(x - 1.0, next)));
        }
        else
        {
            return Enumerable.Range(1, 100).
                Aggregate<int, double>(0.0, (sum, next) =>
                    sum + 1.0 / next * IntPower((x - 1) / x, next));
        }
    }

    static double DoublePower(double x, double y)
    {
        return Exp(y * Log(x));
    }

```

# Answer
> 15 votes
# C++

How about some template meta programming? It bends what little rules there were, but it's worth a shot:

```
#include <iostream>

template <int pow>
class tmp_pow {
public:
    constexpr tmp_pow(float base) :
        value(base * tmp_pow<pow-1>(base).value)
    {
    }
    const float value;
};

template <>
class tmp_pow<0> {
public:
    constexpr tmp_pow(float base) :
        value(1)
    {
    }
    const float value;
};

int main(void)
{
    tmp_pow<5> power_thirst(2.0f);
    std::cout << power_thirst.value << std::endl;
    return 0;
}

```

# Answer
> 15 votes
## Python

```
def power(x,y):
    return eval(((str(x)+"*")*y)[:-1])

```

Doesn't work for noninteger powers.

# Answer
> 10 votes
# Python

If `y` is a positive integer

```
def P(x,y):
    return reduce(lambda a,b:a*b,[x]*y)

```

# Answer
> 10 votes
# Haskell - 25 chars

```
f _ 0=1
f x y=x*f x (y-1)

```

Following Marinus' APL version:

```
f x y = product $ take y $ repeat x

```

With mniip's comment and whitespace removed, 27 chars:

```
f x y=product$replicate y x

```

# Answer
> 7 votes
# JavaScript (ES6), 31

```
// Testable in Firefox 28
f=(x,y)=>eval('x*'.repeat(y)+1)

```

**Usage:**

```
> f(2, 0)
1
> f(2, 16)
65536

```

**Explanation:**

The above function builds an expression which multiply `x` `y` times then evaluates it.

# Answer
> 6 votes
I'm surprised to see that nobody wrote a solution with the Y Combinator, yet... thus:

# Python2

```
Y = lambda f: (lambda x: x(x))(lambda y: f(lambda v: y(y)(v)))
pow = Y(lambda r: lambda (n,c): 1 if not c else n*r((n, c-1)))

```

No loops, No vector/list operations and No (explicit) recursion!

```
>>> pow((2,0))
1
>>> pow((2,3))
8
>>> pow((3,3))
27

```

# Answer
> 5 votes
# C# : 45

Works for integers only:

```
int P(int x,int y){return y==1?x:x*P(x,y-1);}

```

# Answer
> 5 votes
# bash & sed

No numbers, no loops, just an embarrasingly dangerous glob abuse. Preferably run in an empty directory to be safe. Shell script:

```
#!/bin/bash
rm -f xxxxx*
eval touch $(printf xxxxx%$2s | sed "s/ /{1..$1}/g")
ls xxxxx* | wc -l
rm -f xxxxx*

```

# Answer
> 5 votes
# Javascript

```
function f(x,y){return ("1"+Array(y+1)).match(/[\,1]/g).reduce(function(l,c){return l*x;});}

```

Uses regular expressions to create an array of size y+1 whose first element is 1. Then, reduce the array with multiplication to compute power. When y=0, the result is the first element of the array, which is 1.

Admittedly, my goal was i) not use recursion, ii) make it obscure.

# Answer
> 5 votes
# Mathematica

```
f[x_, y_] := Root[x, 1/y]

```

Probably cheating to use the fact that x^(1/y) = y√x

# Answer
> 4 votes
# Golfscript, 8 characters (including I/O)

```
~])*{*}*

```

Explanation:

TLDR: another "product of repeated array" solution.

The expected input is two numbers, e.g. `2 5`. The stack starts with one item, the string `"2 5"`.

```
Code     - Explanation                                             - stack
                                                                   - "2 5"
~        - pop "2 5" and eval into the integers 2 5                - 2 5
]        - put all elements on stack into an array                 - [2 5]
)        - uncons from the right                                   - [2] 5
*        - repeat array                                            - [2 2 2 2 2]
{*}      - create a block that multiplies two elements             - [2 2 2 2 2] {*}
*        - fold the array using the block                          - 32

```

# Answer
> 3 votes
## Ruby

```
class Symbol
  define_method(:**) {|x| eval x }
end

p(:****[$*[0]].*(:****$*[1]).*('*'))

```

Sample use:

```
$ ruby exp.rb 5 3
125
$ ruby exp.rb 0.5 3
0.125

```

This ultimately is the same as several previous answers: creates a y-length array every element of which is x, then takes the product. It's just gratuitously obfuscated to make it look like it's using the forbidden `**` operator.

# Answer
> 3 votes
# C, exponentiation by squaring

```
int power(int a, int b){
    if (b==0) return 1;
    if (b==1) return a;
    if (b%2==0) return power (a*a,b/2);
    return a*power(a*a,(b-1)/2);
}

```

golfed version in **46 bytes** (thanks ugoren!)

```
p(a,b){return b<2?b?a:1:p(a*a,b/2)*(b&1?a:1);}

```

should be faster than all the other recursive answers so far o.O

slightly slower version in **45 bytes**

```
p(a,b){return b<2?b?a:1:p(a*a,b/2)*p(a,b&1);}

```

# Answer
> 3 votes
# JavaScript

```
function f(x,y){return y--?x*f(x,y):1;}

```

# Answer
> 3 votes
## Haskell - 55

```
pow x y=fix(\r a i->if i>=y then a else r(a*x)(i+1))1 0

```

There's already a shorter Haskell entry, but I thought it would be interesting to write one that takes advantage of the `fix` function, as defined in `Data.Function`. Used as follows (in the Repl for the sake of ease):

```
ghci> let pow x y=fix(\r a i->if i>=y then a else r(a*x)(i+1))1 0
ghci> pow 5 3
125

```

# Answer
> 2 votes
# Q

9 chars. Generates array with `y` instances of `x` and takes the product.

```
{prd y#x}

```

Can explicitly cast to float for larger range given int/long x:

```
{prd y#9h$x}

```

# Answer
> 2 votes
Similar logic as many others, in PHP:

```
<?=array_product(array_fill(0,$argv[2],$argv[1]));

```

Run it with `php file.php 5 3` to get 5^3

# Answer
> 2 votes
I'm not sure how many upvotes I can expect for this, but I found it somewhat peculiar that I *actually* had to write that very function today. And I'm *pretty sure* this is the first time any .SE site sees this language (website doesn't seem very helpful atm).

# ABS

```
def Rat pow(Rat x, Int y) =
    if y < 0 then
        1 / pow(x, -y)
    else case y {
        0 => 1;
        _ => x * pow(x, y-1);
    };

```

Works for negative exponents and rational bases.

I highlighted it in Java syntax, because that's what I'm currently doing when I'm working with this language. Looks alright.

# Answer
> 2 votes
# Pascal

The challenge did not specify the type or range of x and y, therefore I figure the following Pascal function follows all the given rules:

```
{ data type for a single bit: can only be 0 or 1 }
type
  bit = 0..1;

{ calculate the power of two bits, using the convention that 0^0 = 1 }
function bitpower(bit x, bit y): bit;
  begin
    if y = 0
      then bitpower := 1
      else bitpower := x
  end;

```

No loop, no built-in power or exponentiation function, not even recursion or arithmetics!

# Answer
> 2 votes
## J - 5 or 4 bytes

Exactly the same as marinus' APL answer.

For `x^y`:

```
*/@$~

```

For `y^x`:

```
*/@$

```

For example:

```
   5 */@$~ 6
15625
   6 */@$ 5
15625

```

`x $~ y` creates a list of `x` repeated `y` times (same as `y $ x`

`*/ x` is the product function, `*/ 1 2 3` -\> `1 * 2 * 3`

# Answer
> 1 votes
# Python

```
from math import sqrt

def pow(x, y):
    if y == 0:
        return 1
    elif y >= 1:
        return x * pow(x, y - 1)
    elif y > 0:
        y *= 2
        if y >= 1:
            return sqrt(x) * sqrt(pow(x, y % 1))
        else:
            return sqrt(pow(x, y % 1))
    else:
        return 1.0 / pow(x, -y)

```

# Answer
> 1 votes
# Javascript

With tail recursion, works if `y` is a positive integer

```
function P(x,y,z){z=z||1;return y?P(x,y-1,x*z):z}

```

# Answer
> 1 votes
# Bash

Everyone knows `bash` can do whizzy map-reduce type stuff ;-)

```
#!/bin/bash

x=$1
reduce () {
    ((a*=$x))
}
a=1
mapfile -n$2 -c1 -Creduce < <(yes)
echo $a

```

---

If thats too trolly for you then there's this:

```
#!/bin/bash

echo $(( $( yes $1 | head -n$2 | paste -s -d'*' ) ))

```

# Answer
> 1 votes
# Mathematica

This works for integers.

```
f[x_, y_] := Times@@Table[x, {y}]

```

**Example**

```
f[5,3]

```

> 125

---

**How it works**

`Table` makes a list of `y` `x`'s. `Times` takes the product of all of them.\`

---

**Another way to achieve the same end**:

```
#~Product~{i,1,#2}&

```

**Example**

```
#~Product~{i, 1, #2} & @@ {5, 3}

```

> 125

# Answer
> 1 votes
# JavaScript  ~~formerly 44~~  , now 41

```
f=(x,y)=>y?eval(Array(y).join(x+"*")+x):1

TESTING:
alert(f(5,3))
OUTPUT (alert): 125
alert(f(6,3))
OUTPUT (alert): 216
alert(f(8,0))
OUTPUT (alert): 1

```

Changes, altered logic to allow reversed execution, thus removing 3 characters...

Only works for positive integers

# Answer
> 1 votes
## Scala - 47

```
def p(x:Int,y:Int)=(1 to y).fold(1)((a,b)=>a*x)

```

Not dissimilar to the other functional versions that use a variant of `repeat` or `replicate`, with the exception that it takes a *lot* of characters to repeat something in Scala (Stream.continually(x).take(y)).

This version iterates over the range of 1..y, but completely throws out the captured value at each step, instead multiplying the accumulator by the base value 'x'. I was originally going to use `map` to transform the range into all instances of the value x, and use the `product` function to multiply it, but this version is actually a bit shorter.

Usage

```
scala> def p(x:Int,y:Int)=(1 to y).fold(1)((a,b)=>a*x)
p: (x: Int, y: Int)Int

scala> p(5,3)
res44: Int = 125

```

# Answer
> 1 votes
# C

Yet another recursive exponentiation by squaring answer in C, but they do differ (this uses a shift instead of division, is slightly shorter and recurses one more time than the other):

```
e(x,y){return y?(y&1?x:1)*e(x*x,y>>1):1;}

```

# Answer
> 1 votes
## perl

Here's a tail recursive perl entry. Usage is echo $X,$Y | foo.pl:

```
($x,$y) = split/,/, <>;
sub a{$_*=$x;--$y?a():$_}
$_=1;
print a

```

Or for a more functional-type approach, how about:

```
($x,$y) = split/,/, <>;
$t=1; map { $t *= $x } (1..$y);
print $t

```

# Answer
> 1 votes
## Java 8

```
public long power(long num, int pow) {
    return LongStream.rangeClosed(1, pow).reduce(1, (i, j) -> i * num);
}

```

does not work with negative powers.

# Answer
> 1 votes
# Python

```
def getRootOfY(x,y):
   return x**y

def printAnswer():
   print "answer is ",getRootOfY(5,3)
printAnswer()

answer =125

```

I am not sure if this is against the requirements, but if not here is my attempt.

# Answer
> 1 votes
## Windows Batch

Like most of the other answers here, it uses recursion.

```
@echo off
set y=%2
:p
if %y%==1 (
set z=%1
goto :eof
) else (
    set/a"y-=1"
    call :p %1
    set/a"z*=%1"
    goto :eof
)

```

x^y is stored in the environment variable `z`.

# Answer
> 1 votes
```
public static void main(String[] argv) {
    int v=getpow(4,3);
    System.out.println(v);
    }
public static int getpow(int b, int v) {
     if (v == 0) {
        return 1;
    } else {
        return b * getpow(b, v - 1);
    }
}

```

Java: I/P: 3 and 4 O/P: 64

# Answer
> 1 votes
It's important to return a precise answer, and to support large numbers -

```
public static BigInteger power(int x, int y) {
    return (y > 0) ? power(new BigInteger(String.valueOf(x)), y)
            : BigInteger.ONE;
}

public static BigInteger power(BigInteger x, int y) {
    return (y > 0) ? power(x, y - 1).multiply(x) : BigInteger.ONE;
}

public static void main(String[] args) {
    // From here
    // http://en.wikipedia.org/wiki/Power_of_two
    String result = "13,407,807,929,942,597,099,574,024,998,205,846,127,479,365,820,592,"
            + "393,377,723,561,443,721,764,030,073,546,976,801,874,298,166,903,427,690,"
            + "031,858,186,486,050,853,753,882,811,946,569,946,433,649,006,084,096";
    result = result.replace(",", "");
    System.out.println(result.equals(power(2, 512).toString()));
}

```

Of course, the output is

```
true

```

# Answer
> 1 votes
# Javascript/HTML, cheater's (DIY) way:

```
function (a, b) { return "" + a + "<sup>" + b + "</sup>"; }

```

example run: http://jsfiddle.net/r4LfF/1/ (click "run" if it doesn't show up automatically)
maybe it can be done better, but I don't know Javascript!..

# Answer
> 1 votes
Simple recursive Python solution, works when y is non-negative integer:

```
def f(x, y):
    return 1 if y == 0 else x * f(x, y - 1)

```

# Answer
> 1 votes
# ECMAScript 6 (32 bytes):

```
p=(x,y)=>y>2?p(x,--y)*x:+!y||x*x

```

Defines a function named `p` which takes `x` and `y` as parameters, and returns `x` to the power of `y`, without using any built-in functions, or loops.

# Answer
> 1 votes
**C, 79**

This is an optimized version of the standard recursive call. It refactors each successive call by powers of 2. In other words if y is 2^n, it will be called n times.

```
typedef uint64_t Z;Z p(Z x,Z y){return(!y)?1:(1==y)?x:((y&1)?x:1)*p(x*x,y>>1);}

```

# Answer
> 1 votes
## R

A cheap trick for positive integer-valued `y`:

```
hacky <- function(x, y) Reduce(`*`, rep(x, y))

```

And an approximation for real-valued `y`. As far as I'm aware, `apply` is not technically implemented as a loop:

```
mathy <- function(x, y, nterms) {
  sum(sapply(seq_len(nterms), function(i) Reduce(`*`, rep(y * log(x), i)) / factorial(i))) + 1
}

```

This one computed x^y=exp(y\*log(x)) by taking the Taylor expansion of the right hand side. It can also be done recursively if you're leery of `apply`:

```
recursive <- function(x, y, nterms) {
  taylor <- function(n) {
    if(n==0) z <- 1
    else z <- Reduce(`*`, rep(y * log(x), n)) / factorial(n) + taylor(n-1)
    z
  }
  taylor(nterms)
}

```

And the *coup-de-grace*:

```
goofy <- function(x, y, nterms) {
  eval(parse(text = paste(
    sprintf("Reduce(`*`, (%s * log(%s))^%i) / factorial(%i)", y, x, 0:nterms, 0:nterms),
    collapse=" + "
  )))
}

```

---

I ran some single-run benchmarks for fun. Formatting them for looking pretty here is going to be more of a pain than it's worth, but I was surprised to see that the `apply` version was actually slower than the recursive version for small numbers of terms, and that their timings converged up to the maximum number of terms (171, the largest integer that `factorial` will accept). The text-based version was slower still for small numbers of terms, but was actually twice as fast for the large number of terms. They obviously fail dramatically compared to R's built-in versions.

Interestingly, it seems like R (or the package I'm using to benchmark, `microbenchmark`) does some magic in its innards, and when I set `microbenchmark` to use more than one trial all of the times drop by several orders of magnitude. The variation follows a similar pattern, but the differences are now in nanoseconds rather than logarithms of miliseconds.

# Answer
> 1 votes
# Python

```
def pow (x, y):
    class Num:
        n = 1
        def __eq__ (self, v):
            Num.n *= v
            return False
    x in [Num()] * y
    return Num.n

x=2
y=3
print(pow(x, y))

```

Weirdo.

# Answer
> 1 votes
# TI-BASIC

*For TI-83/84 calculators*

```
:Input X,Y
:Lbl 1
:Y-1->Y
:X*X->X
:If 1<Y
:Goto 1
:X

```

Displays/returns `X`

# Answer
> 1 votes
Pascal;

```
FUNCTION pwr(base,power:REAL):REAL;    // calculates base**power for base >0.0
BEGIN
  IF base > 0.0 THEN pwr := EXP(power*LN(base)) ELSE HALT(1);
END;

```

# Answer
> 1 votes
# C++

Since most answers use some language quirks to get things done, i thought about trying to spice things up using quirks of data types themselves. Following function uses integer representation of IEEE float to get a logarithm approximation.

Blazingly fast and inaccurate.

```
float fapxpow(float x, float y) {
    __int32 lx = *(__int32 *)&x;
    lx = (lx - 0x3F7A7DD3)*y + 0x3F7A7DD3;
    float xy = *(float *)&lx;
    return xy;
}

```

# Answer
> 1 votes
# R

```
f=function(x,y) prod(c(rep(x,y)))

```

Not super sure about 'prod', I didn't check how it's implemented. I might just be calling a loop here.

# Answer
> 0 votes
## F#

Since `^` and `**` were already taken and infix operators are fun, let's call it `^^`

```
let rec (^^) (x: int) y =
  let fx = float x
  match y with
  | y when y < 0 -> (x ^^ y + 1) / fx
  | 0 -> 1.0
  | y -> (x ^^ y - 1) * fx

```

`x` and `y` are integers and it returns a float, since it handles negative exponents. Call it with `x ^^ y`

# Answer
> 0 votes
# Delphi XE3

Uses a recursive function that will keep calling itself until multiplied according to the power.

Required input like `p^o`

```
var
  p,o:integer;

  function Pwr(n,r,c:integer):integer;
  begin
    if c=o then
      Result:=r
    else
      Result:=Pwr(n,r*p,c+1);
  end;
begin
    readln(p,o);
    Writeln(Pwr(o,p,1));
    readln;
end.

```

Input: `2 5`
Output: `32`

# Answer
> 0 votes
# C

```
int power(int x,int y)
{
if ( y!=1 )
    return (x*power(x,y-1));
}

```

What is this illegal?

# Answer
> 0 votes
## PHP

```
function altpow($x,$y) {
    if ( $y > 0 ) {
        return array_product(array_fill(0,$y,$x));
    } else if ( $y < 0 ) {
        return 1/array_product(array_fill(0,$y*-1,$x));
    }
    return 1;
}

```

Doesn't work with floating point exponents.

Test:

```
pow(4.33,-5) // 0.00065699266096183
altpow(4.33,-5) // 0.00065699266096183

```

# Answer
> 0 votes
**Using C++**

```
#include <iostream>

using namespace std;

float power(float x, float y) {
    if(y  == 0)
    return 1;
    if(y == 1)
    return x;

    return power(x,y-1) *x;

    }

int main()
{
   cout << "Hello World" << endl;

   cout<<power(2,3);

   return 0;
}

```

# Answer
> 0 votes
# Clojure

```
(defn pow [x y]
 (if (= y 0) 1
  (reduce * x (take (- y 1) (repeat x)))))

(pow 2 2)
=> 4

```

It will not work for negative exponent.

# Answer
> 0 votes
## Java 8 lambda recursion

```
    static BinaryOperator<Integer> powerof;
public static void main(String[] args) {
    powerof = (x, y) -> {return y == 0 ? 1 : x * powerof.apply(x, y-1);};
    System.out.println(powerof.apply(5, 3));
}

```

Guess it's kind of late, but I'll post anyway to celebrate the imminent release of java 8 :)

# Answer
> 0 votes
## Another Mathematica Solution, 33 characters

```
D[ExpIntegralEi[(1 + y) Log[x]], x, y]

```

I believe that this does not violate the rule against using "built in power functions", as while the exponential integral function implies E^t dt, it does *not* involve x^y.

This solution is unusual among those posted here in that it works for more than just positive integers, and in fact works for any complex numbers for both x and y.

# Answer
> 0 votes
# Python

```
import math
def recurse_log(x, minimum, cur):
    val = math.log(cur, x)
    if cur == minimum:
        return (val,)
    else:
        return recurse_log(x, minimum, cur-1) + (val,)

def exp(x,y):
    crude_ans = 1<<(int(y*math.log2(x)))
    min_ans = crude_ans//2
    max_ans = crude_ans*2
    possible = list(recurse_log(x, min_ans, max_ans))
    return min_ans + min(range(len(possible)), key=lambda v: abs(possible[v]-y))

```

Works only with integers. This code finds a crude calculation of the answer using log base two and a bitshift (which serves as a base 2 exponents). This gives an answer accurate to the nearest power of two. Then, it takes the log of every integer in the possible range and sees which is closest.

It's very very slow.

# Answer
> 0 votes
# JavaScript, ES5+

This may be bending the rules a bit, due to the use of `forEach`, although it's not being used in the typical fashion.

```
function pwr(x, y){
  var array1 = [], i = 0, result = 1;
  array1.push(function(){i++; result *= x; if(i >= y) throw {};});
  array1.push(function(a){array1.forEach(a)});
  try{
    array1.forEach(array1[1]);
  }
  catch(e){
    return result;
  }
}
console.log(pwr(3,4)); //81

```

`y` must be an integer; `x` does not need to be.

# Answer
> 0 votes
# Jelly - 3 bytes

```
x×/

```

Pretty much identical to the APL and J solutions, but as a newer language Jelly is more efficient.

`x` turns a,b into \[a,a,...,a\] (length b)

`×/` computes reduce(c,d--\>c×d, \[a,a,...,a\]), to get a×a×...×a = a^b.

# Answer
> 0 votes
# F# (.NET Core), 42 bytes

```
fun(x,y)->Seq.reduce(*)<|Seq.replicate y x

```

Try it online!

---
Tags: popularity-contest, math, restricted-source
---


title: Shift the weekday!

text:
# Question
Title: Shift the weekday!
Employers love to see their employees working hard, while the employees would love to work less, especially those with a monthly rather than hourly payment.

The laziest of employees are thinking about the world where every month starts with the same weekday and it makes them wonder if they would work more or less.

The greediest of employers are thinking about the world where every month starts with the same weekday and it makes them wonder if their employees would work more or less.

Your task (as a lazy employee or greedy employer, you choose) is to write the shortest program or function that given weekday every month must start outputs the number of working and weekend days.

## Input

* Weekday identificator. This can be a 0- or 1-based index, case-insensitive shortname (`Mo/Mon`, `Tu/Tue` etc) or case-insensitive full name (`Monday`, `tuesday` etc) as long as you specify the format.

## Output

* One of the following output formats allowed:
    1. A string of single space/comma/semicolon separated values.
    2. A list of values.
    3. A multi-line string of values with a trailing line break allowed.
* The output format must be consistent.
* 2 values must present in the output: number of working days in base 10 and number of weekends in base 10.

## Rules

* Assume the year is 365 days.
* Workdays are Monday, Tuesday, Wednesday, Thursday and Friday.
* Week starts with Monday.
* No national weekends are accounted.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

## Examples

```
 Input  | Output
--------+--------
 Monday | 269 96
    Tue | 269,96
      3 | 269 96   // 1-based index
      3 | 262, 103 // 0-based index
     fr | 251;114
      5 | 247 118  // 0-based index
 sunday | 258;107 // 0-based index

```

# Answer
> 3 votes
# JavaScript (ES6),  ~~34~~  33 bytes

Takes input as a 0-based index. Returns `[weekend_days, working_days]`.

```
i=>[w=96|'5621'[i-3]*11%24,365-w]

```

Try it online!

### How?

The minimum number of weekend days \\$w\_i\\$ being \\$96\\$, we can just store the difference \\$d\_i=w\_i-96\\$ for each possible input and output \\$\[96+d\_i, 365-(96+d\_i)\]\\$.

This gives:

$$\[0,0,0,7,18,22,11\]$$

It's worth noting that \\$96=2^5+2^6\\$ and each value above is less than \\$2^5\\$, which means that we can compute \\$96\text{ OR }d\_i\\$ instead of \\$96+d\_i\\$ and still get the correct result.

We use the following formula to convert \\$i\\$ to \\$d\_i\\$:

$$d\_i=(x\_i\times11)\bmod 24$$

where \\$x\_i\\$ consists of a single decimal digit:

$$\[0,0,0,5,6,2,1\]$$

Hence the JS code:

```
96 | '5621'[d - 3] * 11 % 24

```

For \\$i\<3\\$, `'5621'[d-3]` is *undefined* and `'5621'[d-3]*11%24` results in *NaN*. But because we use a bitwise OR, this is coerced to \\$0\\$ and returns \\$96\\$ as expected.

# Answer
> 3 votes
# Python 3.8 (pre-release), 37 bytes

lambda d:(k:=ord('```grvk'[d]),365-k)
</code></pre>

Monday is `0`, returns a tuple `(weekend days, weekdays)`.

**Try it online!**

# Answer
> 1 votes
# Jelly,  ~~16~~  15 bytes

-1 thanks to Erik the Outgolfer (use of printing in a full-program mode)

<pre><code>ị“```grvk‘Ṅ365_

Monday is `1`, prints `weekend days` then `weekdays` to STDOUT.

**Try it online!**

---

I am not sure how to build data for Jelly's hash function, , but maybe that would be better...

# Answer
> 1 votes
# 05AB1E, 17 bytes

```
.•OζΛ¦•IèÇ<D365αì

```

0-indexed (`0 = Monday; 6 = Sunday`), returns `[working_days, weekend_days]`.

Try it online or verify all test cases.

**Explanation:**

```
.•OζΛ¦•            # Push compressed string "aaahswl"
       Iè          # Index the input-integer into it
         Ç         # Convert the character to its unicode value
          <        # Decrease that by 1
           D365α   # Create a copy, and get its absolute difference with 365
                ì  # Prepend this (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•OζΛ¦•` is `"aaahswl"`.

---
Tags: code-golf
---


title: Repeated reciprocal

text:
# Question
Title: Repeated reciprocal
What you need to do is create a function/program that takes a decimal as input, and outputs the result of repeatedly taking the reciprocal of the fractional part of the number, until the number becomes an integer.

More specifically, the process is as follows:

1. Let x be the input
2. If x is an integer, output it.
3. Otherwise: \\$x \leftarrow \frac{1}{\mathrm{frac}(x)}\\$. Go back to 2.

\\$\mathrm{frac}(x)\\$ is the fractional component of \\$x\\$, and equals \\$x - \left\lfloor x \right\rfloor\\$. \\$\left\lfloor x \right\rfloor\\$ is the floor of x, which is the greatest integer less than \\$x\\$.

Test cases:

```
0 = 0
0.1 = 1/10 -> 10
0.2 = 1/5 -> 5
0.3 = 3/10 -> 10/3 -> 1/3 -> 3
0.4 = 2/5 -> 5/2 -> 1/2 -> 2
0.5 = 1/2 -> 2
0.6 = 3/5 -> 5/3 -> 2/3 -> 3/2 -> 1/2 -> 2
0.7 = 7/10 -> 10/7 -> 3/7 -> 7/3 -> 1/3 -> 3
0.8 = 4/5 -> 5/4 -> 1/4 -> 4
0.9 = 9/10 -> 10/9 -> 1/9 -> 9
1 = 1
3.14 = 157/50 -> 7/50 -> 50/7 -> 1/7 -> 7
6.28 = 157/25 -> 7/25 -> 25/7 -> 4/7 -> 7/4 -> 3/4 -> 4/3 -> 1/3 -> 3

```

Summary for 0 to 1 at increments of 0.1: 0, 10, 5, 3, 2, 2, 2, 3, 4, 9, 1

This is , so fewest bytes wins.

Clarifications:

* "Bonus points" for no round-off error
* Should work for any non-negative rational number (ignoring round-off error)
* You can, but don't have to output the steps taken
* You can take input as a decimal, fraction, or pair of numbers, which can be in a string.

Sorry for all the issues, this is my first question on this website.

# Answer
# J, 18 bytes

```
%@(-<.)^:(~:<.)^:_

```

In J, the idiom `u ^: v ^:_` means "Keep applying the verb `u` while condition `v` returns true.

In our case, the ending condition is defined by the hook `~:<.`, which means "the floor of the number `<.` is not equal `~:` to the number itself" -- so we'll stop when the main verb `u` returns an int.

`u` in this case is another hook `-<.` -- the number minus its floor -- whose return value is fed into `@` the reciprocal verb `%`.

Try it online!
> 5 votes

# Answer
# Mathematica, 36 bytes

```
Last@*ContinuedFraction@*Rationalize

```

### Demo

```
In[1]:= f = Last@*ContinuedFraction@*Rationalize

Out[1]= Last @* ContinuedFraction @* Rationalize

In[2]:= f[0]

Out[2]= 0

In[3]:= f[0.1]

Out[3]= 10

In[4]:= f[0.2]

Out[4]= 5

In[5]:= f[0.3]

Out[5]= 3

In[6]:= f[0.4]

Out[6]= 2

In[7]:= f[0.5]

Out[7]= 2

In[8]:= f[0.6]

Out[8]= 2

In[9]:= f[0.7]

Out[9]= 3

In[10]:= f[0.8]

Out[10]= 4

In[11]:= f[0.9]

Out[11]= 9

In[12]:= f[1]

Out[12]= 1

```
> 6 votes

# Answer
# Python 3, 101 bytes

```
lambda s:g(int(s.replace(".","")),10**s[::-1].index("."))
g=lambda a,b:a and(b%a and g(b%a,a)or b//a)

```

Try it online!

Format: the string must contain a decimal point.
> 5 votes

# Answer
# Perl 6, 42 bytes

```
{($_,{1/($_-.floor)}...*.nude[1]==1)[*-1]}

```

Try it online!

The `nude` method returns the **nu**merator and **de**nominator of a rational number as a two-element list. It's shorter to get the denominator this way than to call the `denominator` method directly.
> 4 votes

# Answer
# PHP, 69 bytes

```
for(;round(1e9*$a=&$argn)/1e9!=$o=round($a);)$a=1/($a-($a^0));echo$o;

```

Try it online!

# PHP, 146 bytes

```
for($f=.1;(0^$a=$argn*$f*=10)!=$a;);for(;1<$f;)($x=($m=max($a,$f))%$n=min($a,$f))?[$f=$n,$a=$x]:$f=!!$a=$m/$n;echo($o=max($a,$f))>1?$o:min($a,$f);

```

Try it online!
> 4 votes

# Answer
# Haskell, 47 bytes

This beats Wheat Wizard's answer because `GHC.Real` allows us to pattern match on rationals using `:%`, aswell as having a shorter name

```
import GHC.Real
f(x:%1)=x
f x=f$1/(x-floor x%1)

```

Try it online!

`f` takes a `Rational` number as input, although ghc allows them to be written in a decimal format, within a certain precision.
> 4 votes

# Answer
# Haskell, ~~40~~ 34 bytes

Edit:

* -6 bytes: @WheatWizard pointed out the fraction can probably be given as two separate arguments.

(Couldn't resist posting this after seeing Haskell answers with verbose imports – now I see some other language answers are also essentially using this method.)

`!` takes two integer arguments (numerator and denominator of the fraction; they don't need to be in smallest terms but the denominator must be positive) and returns an integer. Call as `314!100`.

```
n!d|m<-mod n d,m>0=d!m|0<1=div n d

```

Try it online!

* Ignoring type mismatch, the fractional part of `n/d` (assuming `d` positive) is `mod n d/d`, so unless `mod n d==0`, `!` recurses with a representation of `d/mod n d`.
> 4 votes

# Answer
# Jelly, 8 bytes

```
®İ$%1$©¿

```

Try it online!

Floating-point inaccuracies.
> 3 votes

# Answer
# Python 3 \+ sympy, 67 bytes

```
from sympy import*
k=Rational(input())
while k%1:k=1/(k%1)
print(k)

```

Try it online!

Sympy is a symbolic mathematics package for Python. Because it is symbolic and not binary, there are no floating point inaccuracies.
> 3 votes

# Answer
# JavaScript ES6, 25 bytes

```
f=(a,b)=>a%b?f(b,a%b):a/b

```

Call `f(a,b)` for `a/b`
> 2 votes

# Answer
# Haskell, ~~62~~ 61 bytes

```
import Data.Ratio
f x|denominator x==1=x|u<-x-floor x%1=f$1/u

```

Try it online!

Uses Haskell's `Data.Ratio` library for arbitrary precision rationals. If only the builtin names were not so long.
> 2 votes

# Answer
# JavaScript, 70 bytes

```
x=>(y=(x+'').slice(2),p=(a,b)=>b?a%b?p(b,a%b):a/b:0,p(10**y.length,y))

```

If we can change input type to a string, then it may save 5 bytes.
> 1 votes

# Answer
# APL (Dyalog Classic), 18 bytes

```
{1e¯9>t←1|⍵:⍵⋄∇÷t}

```

Try it online!

# APL NARS, 18 chars

-1 byte thanks to Uriel test

```
f←{1e¯9>t←1|⍵:⍵⋄∇÷t}
v←0 .1 .2 .3 .4 .5 .6 .7 .8 .9 1 3.14
⎕←v,¨f¨v
  0 0  0.1 10  0.2 5  0.3 3  0.4 2  0.5 2  0.6 2  0.7 3  0.8 4  0.9 9  1 1  3.14 7

```
> 1 votes

# Answer
# Smalltalk, 33 bytes

```
[(y:=x\\1)>0]whileTrue:[x:=1/y].x

```
> 1 votes

# Answer
# Stax, 8 bytes

```
ç▄é⌠á◙àù

```

Run and debug it

"Bonus points" for no precision errors. No floating point arithmetic used. This (finally) makes use of stax's built-in rational type.
> 1 votes

---
Tags: code-golf, math, arithmetic, recursion, rational-numbers
---


title: Multiply using ***Real*** numbers

text:
# Question
Title: Multiply using ***Real*** numbers
Inspired by a restriction on What do you get when you multiply 6 by 9? (42)

By order of the President, we are no longer permitted to use confusing fake numbers (i.e. numbers other than integers from 0 to 99 inclusive), and are instead to use only ***real*** numbers, that is, those that are not fake.

Unfortunately, most maths are very unpatriotic at present and thus it is necessary to revolutionalize a new, revised, mathematics for the glory of the State.

Your task is to create a program or function which takes as its input two numbers and provides as its output their product. Your program, obviously, must be consistent with Minitrue's standards for programmatic excellence. Specifically:

* You may use ***real*** numbers in your code; users of fake numbers will be referred to Miniluv
* If a fake number is provided as input, you are to raise an error to that effect raised only in this case. If your chosen language is incapable of error, you are to write a consistent Truthy or Falsy value to a different output stream than normal, this value being written to that output stream only in this case.
* Your program must *never* output any fake numbers; users of fake numbers will by referred to Miniluv
* Your program must output consistently with pre-Ministry math texts, except where those texts are influenced by thoughtcrime (i.e. where the input or output would be a fake number). In those cases, you are free to define whatever truth you think best furthers the Party's goals, provided your output is consistent with above principles.
* Your input is guaranteed to be either two real numbers, two fake numbers, or one real and one fake number

This is code golf; the shortest code in bytes wins.

Some test cases:

```
Input: 0, 3 Output: 0
Input: 2, 5 Output: 10
Input: 9, 11 Output: 99
Input: 10, 10 Output*: 5
Input: -1, 0 Output*: ERROR: THOUGHTCRIME COMMITTED
Input: 2, 2.5 Output*: ERROR: THOUGHTCRIME COMMITTED
Input: 99, 2 Output*: 5
Input: -1, 53 Output*: ERROR: THOUGHTCRIME COMMITTED

```

Test cases with an 'Output\*' indicate that there are multiple valid outputs for that test case.

Please note that while your output in the case of a fake product from real numbers may be an error, it cannot be the *same* error as for fake input (unless both cases trigger), as explained in rule #2.

# Answer
> 2 votes
## Python 2, ~~41~~ ~~38~~ ~~41~~ 39 bytes

```
lambda a,b:a*b%-~99/(chr(a)<'d'>chr(b))

```

-2 bytes from xnor.

Uses `-~99` to get 100 legally.

Relies on `u<v>w` is equivalent to `u<v and v>w`.

If `a` or `b` are not integers `chr` throws a TypeError. If either are less than 0, `chr` throws a ValueError.

If a or b are greater than or equal to 100 (ord('d')), then the denominator will evaluate to 0, and throws a ZeroDivisionError.

Otherwise, the denominator will evaluate to 1; and returns the modded product.

# Answer
> 2 votes
# Python,  ~~54~~  52 bytes

```
lambda a,b:[v for v in(a,b,a*b%-~99)if'd'>chr(v)][2]

```

An unnamed function raising an error if either of the inputs are **fake** otherwise returning the product of the inputs modulo 100 (always **real** and correct if the product itself is **real**).

**Try it online!**

### How?

First creates a tuple of the inputs and their product modulo **100** using `(a,b,a*b%-~99)` where `~x` computes `-1-x` and `%` is the modulo operator.

Then traverses that tuple creating a list of those values which are **real** numbers.

The test for **real**-ness is performed by first attempting to cast each value, `v`, to characters with `chr(v)` \- which will raise a `ValueError` if `v` is not a non-negative integer less than **256**, then checking the value is less than **100** by a less-than-comparison, `<`, to the **100th** character, `'d'`.

If both `a` and `b` are **real** the list will have three entries (the product modulo 100 is alway **real**), otherwise it will have less. The `[...][2]` attempts to get the item at the second index (third item), raising an `IndexError` if it does not exist.

Thus either input being **fake** results in either a `ValueError` or `IndexError`, while both inputs being **real** always succeeds and returns a **real** number, and if that product is itself **real** it is the returned value.

# Answer
> 1 votes
# JavaScript (ES6), ~~61~~ 57 bytes

```
g=x=>x<0|x>99|x%1!=0
f=(a,b)=>g(a)|g(b)|g(a*b)?f(a,b):a*b

```

Similar to the Haskell answer, creates a validation function, called `g`. `g` returns false iff `x` is not a fake number. `f` checks if the either number or the product is fake. If either number or the product is fake, it calls `f` again, which will hit a StackOverflow relatively quickly. Otherwise, it returns the product. Same length, with currying:

```
g=x=>x<0|x>99|x%1!=0
f=a=>b=>g(a)|g(b)|g(a*b)?f(a)(b):a*b

```

```
g=x=>x<0|x>99|x%1!=0
f=(a,b)=>g(a)|g(b)|g(a*b)?f(a,b):a*b

//Note that once one console.log crashes, none of the rest will execute
console.log(f(0,3))
console.log(f(2,5))
console.log(f(9,11))
console.log(f(10,10))
console.log(f(-1,0))
console.log(f("Hello"," World"))
console.log(f("Help",""))
console.log(f(2,2.5))
```

# Answer
> 1 votes
# Python 3, ~~74~~ 69 bytes

*-5 bytes thanks to @Adnan*

```
lambda a,b,h=99+1:a*b%h if type(a)==int==type(b)and 0<=a<h>b>=0else c

```

Try it online!

# Answer
> 1 votes
# Python 3 ~~111~~ ~~101~~ ~~75~~ ~~77~~ 59 bytes

**EDIT**: -10 bytes because of Python's "ternary" operator

**EDIT 2**: -26 bytes because of `lambda` and really obfuscating with the ternary operator.

**EDIT 3**: +2 bytes because `range` is exclusive. Thanks @ovs for catching that

**EDIT 4**: -18 bytes thanks to @ovs's suggestion

```
lambda a,b,s={*range(99+1)}:{a,b}-s and c or max({0,a*b}&s)

```

Try it online!

Raises a Zero Division Error for fake numbers, returns `0` for a fake product

Works by first checking if `a` and `b` are in the range of real numbers. If not, try to access the undefined variable `c`, resulting in an error. Otherwise, return either `0` or `a * b` depending on whether `a * b` is fake or real.

# Answer
> 1 votes
# Jelly,  ~~(16?) 17~~  (13?) 15 bytes

```
⁶Pḟ0r99¤Ȧ$?Dṫ-Ḍ

```

Monadic link taking a list of numbers, yielding the **real** answer if the inputs and the result are **real**, yielding the product modulo **100** if the inputs are **real** but the product would not be, and raising a `TypeError` if either of the inputs are **fake**.

**Try it online!**

13 byte possible alternative (debatable), works in a similar fashion, but uses:

```
⁶Pḟȷ2Ḷ¤Ȧ$?%ȷ2
   ȷ2          - literal 100 (interpreted as 10 raised to the power of 2)
     Ḷ         - lowered range -> [0,1,2,...99] (all the *real* numbers)
           ȷ2  - literal 100 (again)
          %    - modulo

```

### How?

```
⁶Pḟ0r99¤Ȧ$?Dṫ-Ḍ - Main link: list of numbers, [a1, a2]
          ?     - if:
                - ...the if condition:
         $      -   last two links as a monad:
  ḟ             -     filter discard if in:
       ¤        -       nilad followed by link(s) as a nilad:
   0            -         literal zero
     99         -         literal ninety-nine
    r           -         inclusive range -> [0,1,2,...99] - all the *real* numbers
        Ȧ       -     any and all (for our purposes: 0 if empty, 1 otherwise [since zeros were filtered out])
                - ...then:
⁶               -   literal space character
                - ...else:
 P              -   product of [a1, a2]
           D    - convert to a list of it's decimal digits (Type Error
            ṫ-  - tail from index -1 (keep only the last two (or less) digits)
              Ḍ - convert back to a number

```

# Answer
> 1 votes
# Perl 6,  ~~57 54~~  41 bytes

```
{all(@_ X~~Int,$(0..99))??+([*](@_)~~0..99)&&[*] @_!!die}

```

Try it

```
{all(@_ X~~Int,$/=0..99)??+([*](@_)~~$/)&&[*] @_!!die}

```

Try it

```
{all(@_ X~~Int,0..99)??[*](@_)%10²!!die}

```

Try it

Throws an error with the message of `Died` if given a non-**Real** number.
(left intentionally vague to confuse the perpetrator, which gives more time to collect them for re-education)

The first two examples return `0` rather than produce a non-**Real** number.
The third one constrains its result to a **Real** number using the modulus operator.

## Expanded:

```
{  # bare block lambda with implicit parameter list of ｢@_｣

    all(           # check if all tests pass
        @_         # the input
      X~~          # cross ｢X｣ smartmatched ｢~~｣ with the following
        Int,       # All **Real** numbers are Ints
        0..99      # Range of all **Real** numbers
    )

  ??               # if all inputs are **Real** numbers
      [*](@_)      # reduce using &infix:« * » operator
      %            # modulus
      10²          # 10 to the power of 2
  !!               # die if any input was not a **Real** number
    die
}

```

Note that `10²` is parsed as `10` followed by a postfix operator.

# Answer
> 0 votes
# Haskell, 67 bytes

```
v a=not$0<=a&&a<=99
a#b|(v a)||(v b)=error""|v$a*b=error""|True=a*b

```

# Answer
> 0 votes
# Haskell, ~~35~~ 41 bytes

```
a#b|all(`elem`[0..99])[a,b]=mod(a*b)$1+99

```

Try it online!

Example usage: `3#4` returns `12`, while *fake* numbers like `3.5#4`, `300#4` and `(-3)#4` all yield the error `non-exhaustive pattern in function #`. Non-fake inputs whose product would be greater than 99 result in the product modulus 100.

**Edit:** Thanks to Jonathan Allan for pointing out that I initially missed a part of the challenge.

# Answer
> 0 votes
# Ruby, 52 bytes

Returns `NoMethodError` if the input has a fake number.

```
->a,b{a.chr;b.chr;(r=0..99)===a&&r===b ?a*b%-~99:+p}

```

Try it online!

# Answer
> 0 votes
# Java 8, 58 bytes

```
(x,y)->new Long(0>x||x>99||0>y||y>99?"":x*y>99?"0":x*y+"")

```

Try it online!
Throws a NumberFormatException for fake inputs, returns 0 for fake outputs. I added a small easter egg to the TIO example that prints "ERROR: THOUGHTCRIME COMMITTED" if a NumberFormatException is thrown, just for fun.

# Answer
> 0 votes
# , 70 bytes

Probably a cleverer way to do this all the conditionals.

```
function(a,b)`if`(`if`(a<0|a>99|b<0|b>99|a%%1>0|b%%1>0,,a*b)>99,5,a*b)

```

Try it online!

---
Tags: code-golf, restricted-source
---


title: There, I fixed it (with tape)

text:
# Question
Title: There, I fixed it (with tape)
## Challenge:

Given a string only containing upper- and/or lowercase letters (whichever you prefer), put `tape` horizontally to fix it. We do this by checking the difference of two adjacent letters in the alphabet (ignoring wrap-around and only going forward), and filling the space with as much `TAPE`/`tape` as we would need.

---

### Example:

Input: `abcmnnnopstzra`
Output: `abcTAPETAPETmnnnopTAstTAPETzra`

***Why?***

* Between `c` and `m` should be `defghijkl` (length 9), so we fill this with `TAPETAPET`;
* Between `p` and `s` should be `qr` (length 2), so we fill this with `TA`;
* Between `t` and `z` should be `uvwxy` (length 5), so we fill this with `TAPET`.

## Challenge rules:

* The difference only applies forward, so no tape between `zra`.
* It is possible to have multiple of the same adjacent letters like `nnn`.
* You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility.
* You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output, and `TAPE`.
* It is possible no `TAPE` is necessary, in which case the input remains unchanged.

## General rules:

* This is , so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link to a test for your code.
* Also, please add an explanation if necessary.

---

## Test cases:

```
Input:  "abcmnnnopstzra"
Output: "abcTAPETAPETmnnnopTAstTAPETzra"

Input:  "aza"
Output: "aTAPETAPETAPETAPETAPETAPEza"

Input:  "ghijk"
Output: "ghijk"

Input:  "aabbddeeffiiacek"
Output: "aabbTddeeffTAiiaTcTeTAPETk"

Input:  "zyxxccba"
Output: "zyxxccba"

Input:  "abccxxyz"
Output: "abccTAPETAPETAPETAPETAPExxyz"

Input:  "abtapegh"
Output: "abTAPETAPETAPETAPETtaTAPETAPETAPETApeTgh"

Input:  "tape"
Output: "taTAPETAPETAPETApe"

```

# Answer
# 05AB1E, ~~14~~ 12 bytes

```
'¡ÉIÇ¥<∍‚ζJJ

```

Try it online!

**Explanation**

```
'¡É            # push the string "tape"
   I           # push input
    Ç          # convert to a list of character codes
     ¥         # calculate deltas
      <        # decrement
       ∍       # extend the string "tape" to each of these sizes
               # results in an empty string for sizes smaller than zero
        ‚ζ     # zip with input (results in a list of pairs)
          JJ   # join to a list of strings and then to a string

```
> 8 votes

# Answer
# Jelly, 13 bytes

```
OI’“¡ʂƁ»ṁ$€ż@

```

Try it online!

### Explanation

```
OI’“¡ʂƁ»ṁ$€ż@ – Full program. Take a string as a command line argument.
O             – Ordinal. Get the ASCII values of each character.
 I’           – Get the increments (deltas), and subtract 1 from each.
          €   – For each difference I...
   “¡ʂƁ»ṁ$    – Mold the compressed string "tape" according to these values.
                Basically extends / shortens "tape" to the necessary length.
           ż@ – Interleave with the input.

```
> 10 votes

# Answer
# Haskell, 58 bytes

```
f(x:y:r)=x:take(length[x..y]-2)(cycle"TAPE")++f(y:r)
f s=s

```

Try it online! The function `f` recurses over the string and looks at consecutive characters `x` and `y`. `cycle"TAPE"` yields the infinite string `"TAPETAPETAPE..."`. `[x..y]` gets the range of characters from `x` to `y` inclusive, so we need to subtract two from the length. In case `x` occurs later in the alphabet then `y` or both are the same character, we get a negative number after subtracting, but luckily `take` accepts those as well and just takes nothing.
> 7 votes

# Answer
# Perl 5, `-F` 46 bytes

```
#/usr/bin/perl -F
use 5.10.0;
say map{((P,E,T,A)x7)[2..-$^H+($^H=ord)],$_}@F

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~96~~ ~~87~~ 80 bytes

```
lambda s:''.join(c+(C>c)*('TAPE'*6)[:ord(C)+~ord(c)]for c,C in zip(s,s[1:]+' '))

```

Try it online!
> 5 votes

# Answer
# Haskell, 64 bytes

```
t="TAPE"++t
e=fromEnum
f(x:y:z)=x:take(e y-e x-1)t++f(y:z)
f x=x

```

Handles strings of either uppercase *or* lowercase letters, but not both.

Try it online!
> 5 votes

# Answer
# Python 3, 98 bytes

```
lambda a:"".join(sum(zip(a,[("TAPE"*9)[:y>x and~ord(x)+ord(y)]for x,y in zip(a,a[1:])]),()))+a[-1]

```

Try it online!

-1 byte thanks to Asone Tuhid
> 4 votes

# Answer
# C, 84 bytes

```
i,l;f(char*s){for(;*s;)for(putchar(l=*s++),l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);}

```

Try it online!

# C (run on Windows Command Prompt), 81 bytes

```
i,l;f(char*s){for(;putchar(l=*s++);)for(l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);}

```

**Output:**
> 4 votes

# Answer
# Scala, 66 bytes

```
(s:String)=>s./:("z"){(o,c)=>o+("TAPE"*6).take(c-o.last-1)+c}.tail

```

Try it online!

# Explanation

```
/: foldLeft over the string
("z") starting with a non-empty string to we don't have to handle the first iteration in a special way
"TAPE"*6 generate a long enough string of TAPETAPETA...
.take(c-o.last-1) take the difference between this character and the previous (now the last char in the output so far) characters from the TAPETAPETA... string. o.last will always be safe because we start with a non-empty string.
o+...+c append it to the output so far ... and add this character to the end
.tail get rid of the leading z we added

```
> 4 votes

# Answer
# PHP, 85 bytes

```
$s=str_split($argv[1]);foreach($s as$l)echo str_pad($l,ord(next($s))-ord($l),'TAPE');

```

Try it online!

### Explanation

```
$s = str_split($argv[1]);   // convert the parameter string to an array
foreach($s as $l)           // loop the array
echo str_pad(               // print
  $l,                       // the letter
  ord(next($s)) - ord($l),  // calculate the distance to the next letter using ASCII values
  'TAPE'                    // padding string
);                          // profit!

```
> 4 votes

# Answer
# Javascript, ~~131~~ 127 Bytes

4 Bytes saved thanks to Rick Hitchcock.

```
z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))

```

## Unrolled

```
z=a=>[...a].reduce(
  (x,y)=>
    x + [...Array(
      (f = y.charCodeAt()-(x.slice(-1).charCodeAt()) ) > 1 ? (f-1) : 0
    )].reduce(
      (e,r,t)=>
        e + "TAPE"[t%4],"") + y
);

```

My Problem here is that Javascript had no clean way to get the distance between character a and b.

```
<script>
  z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))
</script>

<main>
  <input id="input-box" type="text">
  <pre id=output>output</pre>
</main>

<script>
  inputBox = document.getElementById("input-box");
  inputBox.addEventListener("keyup", function(e){
    output.innerText = z(inputBox.value);
  });
</script>
```
> 3 votes

# Answer
# Python 2 / 3, ~~70~~ 69 bytes

```
f=lambda s,*t:t and s+('TAPE'*6)[:max(ord(t[0])+~ord(s),0)]+f(*t)or s

```

Try it online!
> 3 votes

# Answer
# Charcoal, 20 bytes

```
⭆θ⁺…TAPE∧κ⊖⁻℅ι℅§θ⊖κι

```

Try it online! Explanation:

```
 θ              θ       Input string
⭆                       Map over characters
                  κ     Current index
                 ⊖      Decremented
               §        Index into string
             ι          Current character
            ℅ ℅         Ordinal
           ⁻            Subtract
          ⊖             Decremented
         κ              Current index
        ∧               Logical and
    TAPE                Literal string
   …                    Mold to length
                   ι    Current character
  ⁺                     Concatenate
                        Implicitly print

```
> 2 votes

# Answer
# Java (JDK), 91 bytes

```
s->{var p='z';for(var c:s)System.out.print("ETAP".repeat(9).substring(1,c>p?c-p:1)+(p=c));}

```

Try it online!

## Explanation

```
s->{                       // char[]-accepting lambda consumer, printing a String
 var p='z';                //  store the previous character
 for(var c:s){             //  for each character of the string
  System.out.print(        //   print...
   "ETAP".repeat(9)        //    "ETAP" repeated 9 times (to go above 26 chars)
    .substring(1,          //     of which, we substring c-p -1 characters
     c>p?c-p:1             //
    )                      //
   +(p=c)                  //    and append c, while also storing the previous character
  );

```

## Credits

* -2 bytes thanks to R.M
* -4 bytes thanks to ceilingcat, by upgrading to Java 10+ and switching types to `var`
* -3 bytes thanks to Kevin Cruijssen, by printing the result of my (previously) alternate version instead of returning it
> 2 votes

# Answer
# Ruby, ~~78 77 64~~ 62 bytes

-1 byte thanks to Kevin Cruijssen

```
f=->s,*t{t[0]?s+('TAPE'*6)[0,[0,t[0].ord+~s.ord].max]+f[*t]:s}

```

Try it online!
> 2 votes

# Answer
# Pip, 29 bytes

```
O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa

```

Takes input as a command-line argument (lower- or uppercase, doesn't matter). Try it online!

### Explanation

```
O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa
                               a is 1st cmdline arg; v is -1 (implicit)
O                              Output without newline
 @a                            the first character of a
                          MPa  Map this function to pairs of successive characters of a:
                    Ag          Get the ASCII codes of the two characters
                  $-            Fold on subtraction (i.e. asc(first)-asc(second))
                v-              -1 minus the above (i.e. asc(second)-asc(first)-1)
              [0      ]         A list containing 0 and the above
            MX                  Max of the list
          @<                    The first ^ characters (with cyclic indexing)
    "TAPE"                      of this string
   {                   }.B      Concatenate the second character

```
> 2 votes

# Answer
# JavaScript (ES6), ~~80~~ 78 bytes

```
f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s

```

The distance between two characters can be determined by converting their concatenation to base 36, subtracting 370, modulus 37.

For example, `(parseInt('cy',36)-370)%37 == 22`.

We can then use `padEnd` to fill in the gaps, and recursion to handle the loop.

**Test Cases:**

```
f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s

console.log(f('abcmnnnopstzra'));
console.log(f('aza'));
console.log(f('ghijk'));
console.log(f('aabbddeeffiiacek'));
console.log(f('zyxxccba'));
console.log(f('abccxxyz'));
console.log(f('abtapegh'));
console.log(f('tape'));
```
> 2 votes

# Answer
# K4, 48 bytes

**Solution:**

```
{,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}

```

**Examples:**

```
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"abcmnnnopstzra"
"abcTAPETAPETmnnnopTAstTAPETzra"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aza"
"aTAPETAPETAPETAPETAPETAPEza"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"zyxxccba"
"zyxxccba"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aabbddeeffiiacek"
"aabbTddeeffTAiiaTcTeTAPETk"

```

**Explanation:**

Fairly simple solution, but a high byte count... Find the deltas, take from the string `"TAPE"`, join to the original string cut where the deltas are \> 1.

```
{,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"} / the solution
{                                              } / lambda
                                         "TAPE"  / the string TAPE
                                      #\:        / take each-left
           ,[                      ; ]           / join (,)
                                   0             / zero (ie append zero)
                              "j"$x              / cast input to int
                           -':                   / deltas
                        -1+                      / subtract 1
                      d:                         / assign to d
                    0<                           / delta greater than 0?
                   &                             / indices where true
                 w:                              / assign to w
               d                                 / index into deltas at w
             1_                                  / drop first
         ,'                                      / join each-both
   _[w;x]                                        / cut input x at indices w
 ,/                                              / flatten

```
> 2 votes

# Answer
# Excel VBA, 106 bytes

An anonymous VBE immediate window function that takes input as an uppercase string via cell `A1` and outputs to the VBE immediate window.

```
a=90:For i=1To[Len(A1)]:c=Mid([A1],i,1):b=Asc(c):For j=2To b-a:?Mid("peta",j Mod 4+1,1);:Next:?c;:a=b:Next

```
> 2 votes

# Answer
# Ruby, ~~59~~ 53 bytes

```
->s{s.reduce{|x,y|x+y.rjust(y.ord-x[-1].ord,"TAPE")}}

```

Try it online!

This is actually pretty straightforward - we take input as ~~split our string into~~ an array of chars (thanks to Asone Tuhid for pointing this out) and apply reduce operation, where we justify each char to the required length using "TAPE" as filler string.
> 2 votes

# Answer
# APL (Dyalog Classic), 30 bytes

```
{∊⍵,¨⍨⍴∘'TAPE'¨0,0⌈-1+2-/⎕a⍳⍵}

```

Try it online!

`{ }` anonymous function with argument

`⎕a⍳⍵` find indices of its chars in the alphabet

`2-/` pairwise differences (prev minus next)

`1+` add 1

`-` negate

`0⌈` max(0, ...)

`0,` prepend a 0

`⍴∘'TAPE'¨` reshape cyclically the string `'TAPE'` to each

`⍵,¨⍨` append each char from the argument to the corresponding reshaped string

flatten
> 2 votes

# Answer
# K (oK), 33 bytes

```
{,/((0|-1+0,1_-':x)#\:"TAPE"),'x}

```

Try it online!

`{ }` anonymous function with argument `x`

`-':x` subtract each prior (use an imaginary 0 before the first item)

`1_` drop first item

`0,` prepend a 0

`-1+` add -1

`0|` max(0, ...)

`(`...`)#\:"TAPE"` reshape the string `"TAPE"` to each item from the list on the left

`(`...`),'x` append the corresponding character from `x` to each reshaped string

`,/` concatenate all
> 2 votes

# Answer
# C# (.NET Core), ~~122~~ 111 bytes

Saved 11 bytes thanks to @KevinCruijssen

```
s=>{var r=""+s[0];for(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;)r+="ETAP"[(e-d)%4];return r;}

```

Try it online!

**Explanation:**

```
s =>
{
    var r = "" + s[0];                  //Declare string for the result and initialize with the first character from the input.
    for (                               //Loop over the input,
        int i = 1, e, d;                //starting with the second character, also declare helper variables.
        i < s.Length;                   //Loop until the end of the input is reached.
        r += s[i++])                    //Add the current character to the result and increase the counter.
        for (                           //Loop for adding the TAPE.
            e = d = s[i] - s[i - 1];    //Calculate the differnce between the current and the previous character.
            d-- > 1;)                   //Loop until the difference is 1.
            r += "ETAP"[(e - d) % 4];   //Add a character from the TAPE to the result.
    return r;                           //Return the result.
}

```
> 1 votes

# Answer
# Python 3, 90 bytes

```
p,o=' ',''
for t in input():y=(ord(t)-ord(p)-1)*(p!=' ');o+=('TAPE'*y)[0:y]+t;p=t
print(o)

```

Try it Online
> 1 votes

# Answer
# Yabasic, 119 bytes

An anonymous function that takes input as an uppercase string and outputs to STDOUT.

```
Input""s$
a=90
For i=1To Len(s$)
c$=Mid$(s$,i,1)
b=Asc(c$)
For j=2To b-a
?Mid$("peta",Mod(j,4)+1,1);
Next
?c$;
a=b
Next

```

Try it online!
> 1 votes

# Answer
# Clojure, 139 119 bytes

```
#(reduce-kv(fn[r x c](let[a(cycle "TAPE")i int d(-(i(nth(cycle %)(inc x)))(i c))](str r(if(> d 1)(apply str c(take(dec d)a))c))))""(vec %))

```

Anonymous function which take the string and returns the taped one. As always, Clojure doesn't seem to perform all too well. What I couldn't really work out is fetching the next char in a short way. On the last char I would get an `OutOfBoundsException`, reason obvious. So I put a `cycle` around it. Maybe there is a more elegant solution.

## Ungolfed

```
#(reduce-kv
  (fn [r x c]
    (let [a (cycle "TAPE")
          i int
          d (-
             (i (nth (cycle %) (inc x)))
             (i c))]
      (str r
           (if (> d 1)
             (apply str c (take (dec d) a))
             c))))
  ""
  (vec %))

```

# Update

Managed to shafe off a few bytes. Got rid of the pesky `if` statement by decrementing the difference. `take` produces an empty list if the number is 0 or less which in turn results in an empty string.

```
#(reduce-kv(fn[r x c](let[d(-(int(nth(cycle %)(inc x)))(int c)1)](str r c(apply str(take d(cycle "TAPE"))))))""(vec %))

```

## Ungolfed

```
#(reduce-kv
  (fn [r x c]
    (let [d (-
             (int (nth (cycle %) (inc x)))
             (int c)
             1)]
      (str
       r
       c
       (apply
        str
        (take
         d
         (cycle "TAPE"))))))
  ""
  (vec %))

```
> 1 votes

# Answer
# CJam, ~~27~~ 25 bytes

```
q_:i2ew.{:-~0e>_"TAPE"*<}

```

Try it online!

Far, far from the other golfing languages, but I'm proud of this golf anyway.

### Explanation

```
q                            Read the input
     ew                      And take windows of size
    2                          2
   i                           from the code points
  :                            of each of its characters.
        {               }    For each of these windows:
         :                     Reduce with
          -                      subtraction.
                                 Since there are only 2 elements, this just subtracts them.
             e>                Take the maximum
           ~                     of this difference's bitwise negation
            0                    and zero.
                                 This returns -n-1 if n is negative, and 0 otherwise.
                                 Call this new value m.
                      *        Repeat
                "TAPE"           the string "TAPE" m times.
               _       <       And then take the first m elements.
                             The result of this will be an array of strings which consist of
                             the string "TAPE" repeated the proper amount of times.
       .                     Zip this array with the original input.
                             Since the original input is one element longer than this array,
                             the nothing is pushed after the final character.
                             Implicitly print everything.

```
> 1 votes

# Answer
# Husk, ~~26~~ 25 bytes

```
ΣSoż+C1(moo↑¢¨tȦ9¨>0←Ẋ-mc

```

Try it online!
> 1 votes

# Answer
# PowerShell, 72 bytes

```
-join($args|% t*y|%{for(;$p*(++$p-lt$_)){'TAPE'[$i++%4]}$i=0;$p=+$_;$_})

```

Try it online!
> 1 votes

# Answer
# **Java , 213 166 153 bytes**

```
i->{String o="";for(int a=0,l=i.length;++a<=l;){char u=i[a-1],n;o+=u;if(a<l){n=i[a];o+="TAPETAPETAPETAPETAPETAPET".substring(0,n-u>0?n+~u:0);}}return o;}

```

try it online

```
    String o = "";
    for (int a = 0, l = i.length; ++a <= l; ) {              // for each character
        char u = i[a - 1];                                    //  current character
        o += u;                                               //  add current character to output string
        if (a < l) {                                          //  if it's not the last one
            char n = i[a];                                    //  next character
            o += "TAPETAPETAPETAPETAPETAPET".substring(0, n - u > 0 ? n +~ u : 0); // fill with enough tape but only forward
        }
    }
    return o;

```

Please help me make it better.

Thanks to @cairdcoinheringaahing for the tip on whitespaces. Thanks to @R.M for the tip on tape string. Thanks to @KevinCruijssen for the lambda and expressions tips.
> 0 votes

---
Tags: code-golf, string
---


title: Am I perfect (number)?

text:
# Question
Title: Am I perfect (number)?
This is my first challenge!

### Background

Perfect number is a positive integer, that is equal to the sum of all its divisors, except itself.
So `6` is perfect number, since `1 + 2 + 3 = 6`.
On the other hand `12` is not, because `1 + 2 + 3 + 4 + 6 = 16 != 12`.

### Task

Your task is simple, write a program, which will, for given `n`, print one of these messages:

> I am a perfect number, because `d1 + d2 + ... + dm = s == n`
> I am not a perfect number, because `d1 + d2 + ... + dm = s [<>] n`

Where
`d1, ... dm` are all divisors of `n` except for `n`.
`s` is the sum of all divisors `d1, ..., dm` (again, without `n`).
`[<>]` is either `<` (if `s < n`) or `>` (if `s > n`).

### Examples

For `n` being `6`: "I am a perfect number, because 1 + 2 + 3 = 6 == 6"
For `n` being `12`: "I am not a perfect number, because 1 + 2 + 3 + 4 + 6 = 16 \> 12"
For `n` being `13`: "I am not a perfect number, because 1 = 1 \< 13"

### Rules

* `n` is not bigger than your language's standard `int`.
* You can read `n` from standard input, from command line arguments or from a file.
* Output message has to be printed on standard output and no additional characters can appear in the output (it may have trailing whitespace or newline)
* You may not use any built-ins or library functions which would solve the task (or its main part) for you. No `GetDivisors()` or something like that.
* All other standard loopholes apply.

### Winner

This is so shortest code in **bytes** wins!

# Answer
> 4 votes
# Pyth, 81 bytes

```
jd[+WK-QsJf!%QTStQ"I am"" not""a perfect number, because"j" + "J\=sJ@c3"==<>"._KQ

```

Try it online: Demonstration or Test Suite

### Explanation:

```
                                 implicit: Q = input number
               StQ               the range of numbers [1, 2, ..., Q-1]
          f                      filter for numbers T, which satisfy:
           !%QT                     Q mod T != 0
         J                       save this list of divisors in J
      -QsJ                       difference between Q and sum of J
     K                           save the difference in K

jd[                              put all of the following items in a list
                                 and print them joined by spaces:
                  "I am"           * "I am"
   +WK                  " not"       + "not" if K != 0
"a perfect number, because"        * "a perfect ..."
j" + "J                            * the divisors J joined by " + "
       \=                          * "="
         sJ                        * sum of J
            c3"==<>"               * split the string "==<>" in 3 pieces:
                                        ["==", "<", ">"]
           @        ._K              and take the (sign of K)th one (modulo 3)
                       Q           * Q

```

# Answer
> 9 votes
# Java, ~~255~~ 270 bytes (Still FF in base 17)

```
class C{public static void main(String[]a){int i=new Integer(a[0]),k=0,l=0;a[0]=" ";for(;++k<i;)if(i%k<1){l+=k;a[0]+=k+" ";}}System.out.print("I am "+(l==i?"":"not ")+"a perfect number, because "+a[0].trim().replace(" "," + ")+" = "+l+(l==i?" == ":l<i?" < ":" > ")+i);}}

```

And a more readable version:

```
class C {
    public static void main(String[] a) {
        int i = new Integer(a[0]), k = 0, l = 0;
        a[0] = " ";
        for(; ++k<i ;){
            if (i % k == 0) {
                l += k;
                a[0] += k + " ";
            }
        }
        System.out.print("I am " + (l == i ? "" : "not ") + "a perfect number, because " + a[0].trim().replace(" "," + ") + " = " + l + (l == i ? " == " : l < i ? " < " : " > ") + i);
    }
}

```

Previously didn't work for odd numbers, so I had to tweak a few things. At least I got lucky with the byte count again. :)

# Answer
> 6 votes
# R, ~~158~~ ~~163~~ ~~157~~ ~~153~~ ~~143~~ 141 bytes

Still room to golf this I think.
**Edit:** Replaced `if(b<n)'<'else if(b>n)'>'else'=='` with `c('<'[b<n],'>'[b>n],'=='[b==n])`. The `paste(...)` is replaced with an `rbind(...)[-1]`. Thanks @plannapus for a couple more bytes.

```
n=scan();a=2:n-1;b=sum(w<-a[!n%%a]);cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)

```

Ungolfed

```
n<-scan()             # get number from stdin
w<-which(!n%%1:(n-1)) # build vector of divisors
b=sum(w)              # sum divisors
cat('I am',           # output to STDOUT with a space separator
    'not'[b!=n],      # include not if b!=n
    'a perfect number, because',
    rbind('+',w)[-1], # create a matrix with the top row as '+', remove the first element of the vector
    '=',
    b,                # the summed value
    c(                # creates a vector that contains only the required symbol and ==
        '<'[b<n],     # include < if b<n
        '>'[b>n],     # include > if b>n
        '=='
    )[1],             # take the first element
    n                 # the original number
)

```

Test run

```
> n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)
1: 6
2:
Read 1 item
I am a perfect number, because 1 + 2 + 3 = 6 == 6
> n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)
1: 12
2:
Read 1 item
I am not a perfect number, because 1 + 2 + 3 + 4 + 6 = 16 > 12
> n=scan();b=sum(w<-which(!n%%1:(n-1)));cat('I am','not'[b!=n],'a perfect number, because',rbind('+',w)[-1],'=',b,c('<'[b<n],'>'[b>n],'==')[1],n)
1: 13
2:
Read 1 item
I am not a perfect number, because 1 = 1 < 13
>

```

# Answer
> 5 votes
# Python 2, ~~183~~ ~~173~~ 170 bytes

```
b=input();c=[i for i in range(1,b)if b%i<1];d=sum(c);print'I am %sa perfect number because %s = %d %s %d'%('not '*(d!=b),' + '.join(map(str,c)),d,'=<>='[cmp(b,d)%3::3],b)

```

Examples:

```
$ python perfect_number.py <<< 6
I am a perfect number because 1 + 2 + 3 = 6 == 6
$ python perfect_number.py <<< 12
I am not a perfect number because 1 + 2 + 3 + 4 + 6 = 16 > 12
$ python perfect_number.py <<< 13
I am not a perfect number because 1 = 1 < 13
$ python perfect_number.py <<< 100
I am not a perfect number because 1 + 2 + 4 + 5 + 10 + 20 + 25 + 50 = 117 > 100
$ python perfect_number.py <<< 8128
I am a perfect number because 1 + 2 + 4 + 8 + 16 + 32 + 64 + 127 + 254 + 508 + 1016 + 2032 + 4064 = 8128 == 8128

```

Thanks to xnor for saving 13 bytes!

# Answer
> 4 votes
# Julia, ~~161~~ 157 bytes

```
n=int(ARGS[1])
d=filter(i->n%i<1,1:n-1)
s=sum(d)
print("I am ",s!=n?"not ":"","a perfect number, because ",join(d," + ")," = $s ",s<n?"<":s>n?">":"=="," $n")

```

Ungolfed:

```
# Read n as the first command line argument
n = int(ARGS[1])

# Get the divisors of n and their sum
d = filter(i -> n % i == 0, 1:n-1)
s = sum(d)

# Print to STDOUT
print("I am ",
      s != n ? "not " : "",
      "a perfect number, because ",
      join(d, " + "),
      " = $s ",
      s < n ? "<" : s > n ? ">" : "==",
      " $n")

```

# Answer
> 4 votes
# CJam, 90 bytes

```
"I am"rd:R{R\%!},:D:+R-g:Cz" not"*" a perfect number, because "D'+*'=+D:++'=C+_'=a&+a+R+S*

```

For comparison, printing a single `=` could be achieved in 83 bytes.

Try it online in the CJam interpreter.

### How it works

```
"I am"  e# Push that string.
rd:R    e# Read a Double from STDIN and save it in R.
{       e# Filter; for each I in [0 ... R-1]:
  R\%!  e# Push the logical NOT of (R % I).
},      e# Keep the elements such that R % I == 0.
:D      e# Save the array of divisors in D.
:+R-g   e# Add the divisors, subtract R and compute the sign of the difference.
:Cz     e# Save the sign in C and apply absolute value.
"not "* e# Repeat the string "not " that many times.

" a perfect number, because "

D'+*    e# Join the divisors, separating by plus signs.
'=+D:++ e# Append a '=' and the sum of the divisors.
'=C+    e# Add the sign to '=', pushing '<', '=' or '>'.
_'=a&   e# Intersect a copy with ['='].
+a+     e# Concatenate, wrap in array and concatenate.
        e# This appends "<", "==" or ">".
R+      e# Append the input number.
S*      e# Join, separating by spaces.

```

# Answer
> 2 votes
# Lua, ~~244~~ 231 bytes

Golfed:

```
n=io.read("*n")d={}s="1"t=1 for i=2,n-1 do if n%i==0 then table.insert(d,i)s=s.." + "..i t=t+i end end print(("I am%s a perfect number, because %s = %s"):format(t==n and""or" not", s, t..(t==n and" == "or(t>n and" > "or" < "))..n))

```

Ungolfed:

```
n=io.read("*n")
divisors={}
sequence="1"
sum=1
for i=2,n-1 do
    if n%i==0 then
        table.insert(divisors,i)
        sequence=sequence.." + "..i
        sum=sum+i
    end
end

print(("I am%s a perfect number, because %s = %s"):format(sum==n and""or" not", sequence, sum..(sum==n and" == "or(sum>n and" > "or" < "))..n))

```

# Answer
> 2 votes
# Perl, 148 Bytes

```
$a=<>;$_=join' + ',grep{$a%$_==0}1..$a-1;$s=eval;print"I am ".($s==$a?'':'not ')."a perfect number because $_ = $s ".(('==','>','<')[$s<=>$a])." $a"

```

With line breaks:

```
$a=<>;
$_=join' + ',grep{$a%$_==0}1..$a-1;
$s=eval;
print"I am ".($s==$a?'':'not ')."a perfect number because $_ = $s ".(('==','>','<')[$s<=>$a])." $a"

```

# Answer
> 2 votes
## Ruby, ~~174~~ ~~160~~ ~~155~~ ~~136~~ ~~134~~ ~~128~~ 122 Bytes

```
n=6;a=[*1...n].reject{|t|n%t>0};b=a.inject(:+)<=>n;print"I am#{" not"*b.abs} a perfect number, because ",a*?+,"<=>"[b+1],n

```

Saved another 6 Bytes :)

Thanks to Tips for golfing in Ruby

# Answer
> 2 votes
# JavaScript (ES6), 146

Using template strings, it works in Firefox and latest Chrome.

```
for(n=prompt(),o=t=i=1;++i<n;)n%i||(t+=i,o+=' + '+i)
alert(`I am ${t-n?'not ':''}a perfect number because ${o} = ${t} ${t<n?'<':t>n?'>':'=='} `+n)
```

# Answer
> 1 votes
# C#, 252 bytes

```
class A{static void Main(string[]a){int i=int.Parse(a[0]);var j=Enumerable.Range(1,i-1).Where(o=>i%o==0);int k=j.Sum();Console.Write("I am "+(i!=k?"not ":"")+"a perfect number, because "+string.Join(" + ",j)+" = "+k+(k>i?" > ":k<i?" < ":" == ")+i);}}

```

# Answer
> 1 votes
# Hassium, 285 Bytes

Disclaimer: Works with only the latest version of Hassium due to issues with command line args.

```
func main(){n=Convert.toNumber(args[0]);s=1;l="1";foreach(x in range(2,n-3)){if(n%x==0){l+=" + "+x;s+=x;}}if(s==n)println("I am a perfect number, because "+l+" = "+s+" == "+s);else {print("I am not a perfect number, because "+l+" = "+s);if(s>n)println(" > "+n);else println(" < "+n);}}

```

More readable version:

```
func main() {
    n = Convert.toNumber(args[0]);
    s = 1;
    l = "1";
    foreach(x in range(2, n - 3)) {
            if (n % x== 0) {
                    l += " + " + x;
                    s += x;
            }
    }
    if (s == n)
            println("I am a perfect number, because " + l + " = " + s + " == " + s);
    else {
            print("I am not a perfect number, because " + l + " = " + s);
            if (s > n)
                    println(" > " + n);
            else
                    println(" < " + n);
    }
}

```

# Answer
> 1 votes
# MATLAB, 238

Never going to be the shortest of all languages, but here's my attempt with MATLAB:

```
n=input('');x=1:n-1;f=x(~rem(n,x));s=sum(f);a='not ';b=strjoin(strtrim(cellstr(num2str(f')))',' + ');if(s>n) c=' > ';elseif(s<n) c=' < ';else c=' == ';a='';end;disp(['I am ' a 'a perfect number, because ' b ' = ' num2str(s) c num2str(n)])

```

And this is in a slightly more readable form:

```
n=input();      %Read in the number using the input() function
x=1:n-1;        %All integers from 1 to n-1
f=x(~rem(n,x)); %Determine which of those numbers are divisors
s=sum(f);       %Sum all the divisors
a='not ';       %We start by assuming it is not perfect (to save some bytes)
b=strjoin(strtrim(cellstr(num2str(f')))',' + '); %Also convert the list of divisors into a string
                                                 %where they are all separated by ' + ' signs.
%Next check if the number is >, < or == to the sum of its divisors
if(s>n)
    c=' > ';    %If greater than, we add a ' > ' to the output string
elseif(s<n)
    c=' < ';    %If less than, we add a ' < ' to the output string
else
    c=' == ';   %If equal, we add a ' == ' to the output string
    a='';       %If it is equal, then it is a perfect number, so clear the 'not' string
end

%Finally concatenate the output string and display the result
disp(['I am ' a 'a perfect number, because ' b ' = ' num2str(s) c num2str(n)])

```

I've managed to save 2 more bytes by not using a function. Instead you run the line of code and it requests the number as an input. Once run it displays the output at the end.

# Answer
> 1 votes
## Perl 6, 138 bytes

```
$_=get;
my$c=$_ <=>my$s=[+] my@d=grep $_%%*,^$_;
say "I am {
    'not 'x?$c
  }a perfect number, because {
    join ' + ',@d
  } = $s {
    «> == <»[1+$c]
  } $_"

```

( The count ignores the newlines, and indents, because they aren't needed )

`@d` is the array holding the divisors.
`$s` holds the sum of the divisors.
`$c` is the value of the comparison between the input, and the sum of the divisors.
( effectively `$c` is one of `-1`,`0`,`1`, but is really one of `Order::Less`, `Order::Same`, or `Order::More` )

In `'not 'x?$c`, `?$c` in this case is effectively the same as `abs $c`, and `x` is the string repetition operator.

`«> == <»` is short for `( '>', '==', '<' )`.
Since `$c` has one of `-1,0,1`, we have to shift it up by one to be able to use it to index into a list.

Technically this will work for numbers well above 2⁶⁴, but takes an inordinate amount of time for numbers above 2¹⁶.

# Answer
> 0 votes
# Pyth, 84 bytes

```
jd+,+"I am"*.aK._-QsJf!%QTtUQ" not""a perfect number, because"+.iJm\+tJ[\=sJ@"=<>"KQ

```

Invalid answer, because I refuse to implement `=` and `==` in the same equation.

# Answer
> 0 votes
# Ruby, 164 Bytes

```
->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}

```

# Test

```
irb(main):185:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 6
I am a perfect number, because 1 + 2 + 3 = 6 == 6

irb(main):186:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 12
I am not a perfect number, because 1 + 2 + 3 + 4 + 6 = 16 > 12

irb(main):187:0> ->i{t=(1...i).select{|j|i%j==0};s=t.inject &:+;r=['==','>','<'][s<=>i];puts "I am #{'not ' if r!='=='}a perfect number, because #{t.join(' + ')} = #{s} #{r} #{i}"}.call 13
I am not a perfect number, because 1 = 1 < 13

```

# Answer
> 0 votes
# Emacs Lisp, 302 Bytes

```
(defun p(n)(let((l(remove-if-not'(lambda(x)(=(% n x)0))(number-sequence 1(- n 1)))))(setf s(apply'+ l))(format"I am%s a perfect number, because %s%s = %s %s %s"(if(= s n)""" not")(car l)(apply#'concat(mapcar'(lambda(x)(concat" + "(number-to-string x)))(cdr l)))s(if(= sum n)"=="(if(> sum n)">""<"))n)))

```

Ungolfed version:

```
(defun perfect (n)
  (let ((l (remove-if-not '(lambda (x) (= (% n x) 0))
              (number-sequence 1 (- n 1)))))
    (setf sum (apply '+ l))
    (format "I am%s a perfect number, because %s%s = %s %s %s" (if (= sum n)"" " not") (car l)
        (apply #'concat (mapcar '(lambda (x) (concat " + " (number-to-string x))) (cdr l)))
        sum (if(= sum n)
            "=="
          (if(> sum n)
              ">"
            "<"))
        n)))

```

# Answer
> 0 votes
# Powershell, 164 bytes

```
$a=$args[0]
$b=(1..($a-1)|?{!($a%$_)})-join" + "
$c=iex $b
$d=$a.compareto($c)
"I am $("not "*!!$d)a perfect number, because $b = $c $(("==","<",">")[$d]) $a"

```

A few of the common and not so common PoSh tricks;

* Create the sum, then evaluate it with iex
* Compareto to index the gt, lt, eq array
* !!$d will evaluate to true == 1 for $d = 1 or -1, and false == 0 for $d = 0

# Answer
> 0 votes
# awk, 150

```
n=$0{for(p=i=s=n>1;++i<n;)for(;n%i<1;p+=i++)s=s" + "i;printf"I am%s a perfect number, because "s" = "p" %s "n RS,(k=p==n)?_:" not",k?"==":p<n?"<":">"}

```

Wasted some bytes on making this correct for input `1`. I'm not sure if that is expected.

```
n=$0{
    for(p=i=s=n>1;++i<n;)
        for(;n%i<1;p+=i++)s=s" + "i;
    printf "I am%s a perfect number, because "s" = "p" %s "n RS,
           (k=p==n)?_:" not",k?"==":p<n?"<":">"
}

```

# Answer
> 0 votes
# 05AB1E, 58 bytes

```
„I€ÜIÑ¨©OIÊi'€–}“€…íÀ‚³,ƒ«“®vy'+}\'=®ODI.S"==><"211S£sèIðý

```

Try it online or verify all test cases.

**Explanation:**

```
„I€Ü              # Push dictionary string "I am"
IÑ¨               # Push the divisors of the input-integer, with itself removed
   ©              # Store it in the register (without popping)
    O             # Get the sum of these divisors
     IÊi   }      # If it's not equal to the input-integer:
        '€–      '#  Push dictionary string "not"
“€…íÀ‚³,ƒ«“       # Push dictionary string "a perfect number, because"
®v   }            # Loop `y` over the divisors:
  y'+            '#  Push the divisor `y`, and the string "+" to the stack
      \           # Discard the final "+"
       '=        '# And push the string "="
®O                # Get the sum of the divisors again
  D               # Duplicate it
I.S               # Compare it to the input-integer (-1 if smaller; 0 if equal; 1 if larger)
   "==><"         # Push string "==><"
         211S£    # Split into parts of size [2,1,1]: ["==",">","<"]
              sè  # Index into it (where the -1 will wrap around to the last item)
I                 # Push the input-integer again
ðý                # Join everything on the stack by spaces
                  # (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `„I€Ü` is `"I am"`, `'€–` is `"not"`, and `“€…íÀ‚³,ƒ«“` is `"a perfect number, because"`.

---
Tags: code-golf, number-theory
---