text:
Fastest algorithm to output array containing all integers in range excluding duplicate digits
Input is a single integer in ascending digit order.
The only valid inputs are:
12
123
1234
12345
123456
1234567
12345678
123456789
The only valid output is an array (set; list) of length equal to the factorial of input:
Input - Factorial of input - Output array length
12 -> 1*2 -> 2
123 -> 1*2*3 -> 6
1234 -> 1*2*3*4 -> 24
12345 -> 1*2*3*4*5 -> 120
123456 -> 1*2*3*4*5*6 -> 720
1234567 -> 1*2*3*4*5*6*7 -> 5040
12345678 -> 1*2*3*4*5*6*7*8 -> 40320
123456789 -> 1*2*3*4*5*6*7*8*9 -> 362880
The output array is all integers of input length in lexicographical order.
For example, given input 123 -> factorial of input is 1*2*3=6 -> for each of the six array elements output the input integer and the five remaining integers of the array in lexicographic order -> [123,132,213,231,312,321]. Notice that the last element is always the input integer in reverse order.
Test Cases

Input  Output
`12` ->  `[12,21]` // valid output, ascending numeric order
`12` ->  `[12.0,21.0]` // invalid output, output must be rounded to integer
`123` -> `[123,132,213,231,312,321]` // valid output
`123` -> `[123,132,213,222,231,312,321]` // invalid output: `222` are duplicate digits
`123` -> `[123,142,213,231,213,321]` // invalid output: `142` outside range `1-3`
`123456789` -> `[987654321,...,123456789]` // valid output, descending numeric order
`123456789` -> `[987654321,...,123456798]` // invalid output, `123456798` is greater than the minimum required integer in resulting array `123456789`

Rules

Do not use standard library functions for permutations or combinatorics.
If the algorithm produces an integer greater or less than input minimum or maximum only the integers in the specified range must be output. (Technically, if input is 12345 we could generate all integers to 21 or 12, though for input 12345 the only valid output must be within the range 12345 through 54321).
Output must be an array (set; list) of integers, not strings.
The integers output must not be hardcoded.
The output integers must not include duplicate digits (more than one of the same digit at that array index).

Winning criteria
fastest-code
Hardware, OS
Where submissions will be run

~$ lscpu
Architecture:          i686
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 37
Model name:            Intel(R) Pentium(R) CPU        P6200  @ 2.13GHz
Stepping:              5
CPU MHz:               2133.000
CPU max MHz:           2133.0000
CPU min MHz:           933.0000
BogoMIPS:              4256.26
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              3072K

~$ free -m
              total        used        free      shared  buff/cache   available
Mem:           3769        1193         802         961        1772        1219
Swap:             0           0           0

~$ uname -r
4.8.0-36-lowlatency

Kindly explain the algorithm within the body of the answer.
For languages used other than JavaScript (which will test at Chromium 70) will take the time to install the language and test the code for the time taken to output the requirement, as there is no way (that have found) to provide uniform results as to time for every possible language used to derive output (see this comment).

Fastest-algorithm doesn't work for this. With an upper limit on the input, all solutions are automatically O(1).

@Dennis How so, when there must be comparisons and exclusions? Have simply been adding 9 to the input at code here, which requires a variable amount of comparisons or exclusions for each increment of 9; is that O(1) https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/? "O(1) describes an algorithm that will always execute in the same time (or space) regardless of the size of the input data set.". Unless you are seeing the question differently than here? What tag is appropriate?

The asymptotic complexity isn't an exact formula, but an upper bound. Any finite set is always bounded by a constant. Unless you want to turn your contest into a fastest-code challenge (which would require running all the submissions on the same computer, to decide which one is the fastest), I don't see an easy fix.

@Dennis Will run all submissions on this old machine, yes.

Fastest-code works then. Make sure to include your machine's specs (hardware and OS) in the challenge, so people can tune for it.

@Dennis Will the output of free -m and lspcu suffice?

@Dennis Updated. Kindly state if any content at the question needs clarification.

Sure, that's more than enough.

How about giving this a less clumsy title like "find all permutations of the input" with "- distinct values guaranteed"

@Dennis Is https://tio.run/# the optimal resource for uniformly checking the time code takes to complete? If yes, which of "Real time", "User time" or "Sys. time" is the appropriate measurement of the time the code takes to complete?

Is TIO acceptable for fastest-code questions?

@Dennis Noticed some seeming irregularities when testing the code at the answer and JavaScript code before posting an answer (though am relatively certain the algorithm that am using coded in JavaScript is not the fastest code). Was not sure if when output is "truncated" the timers still run. What do you suggest using or implementing for a common testing solution for this question, or any fastest-code question; use tio anyway?

You shouldn't use any shared computer for timing code; TIO is no exception. Your best bet is to run the code on your own machine.

And the program is terminated, once the output limit is reached.

@Dennis Installed Haskell and Node.js. Will try to first run the Haskell code at answer, then own approach at Node.js. That leaves timing the execution. Will probably be asking you more questions, in order to be in accord with https://codegolf.stackexchange.com/questions/175206/fastest-algorithm-to-output-array-containing-all-integers-in-range-excluding-dup?noredirect=1#comment422143_175206. If you are not interested in answering the questions relevant to to the above, simply say so; and will, in time, find solutions to list all relevant times of code at answers at the question.

So far have been able to compile and run Haskel code following https://wiki.haskell.org/Haskell_in_5_steps though not sure how to measure the time from beginning of execution to output limit reached. Having various issues compiling JavaScript es2016 code to run in nodejs.

@xnor What part of the question is not clear to you?

While it may be "hard to tell exactly what you're asking" according to the reason cited for close votes for several users, it is impossible to "clarify your specific problem or add additional details to highlight exactly what you need" where those users who have voted to close the question citing "unclear what you're asking" have made absolutely no attempt to clarify what is not clear to them at the question.

I think Titus might be on to something in regards to the clarity of your question. If you're asking for digit permutations then you can simply say that. I didn't vote to close but I can agree that the current writeup is a bit clunky if that's all you're asking for.

I think this challenge is not interesting. 1. Output all permutations is a very classical task to do, there are numerous existing fast algorithms. 2. Banning library functions is not going to help anything -- people can copy the code from library. 3. Because there exists algorithms that runs in the time equal to the output size, output printing time is going to be the bottleneck.

@user202729 When have attempted to post a challenging question here users do not understand the question and vote to close https://codegolf.stackexchange.com/questions/173145/ The same response occurred when asked the question at "MathOverflow" https://mathoverflow.net/q/314955/131181 where supposedly "MathOverflow's primary goal is for users to ask and answer research level math questions, the sorts of questions you come across when you're writing or reading articles or graduate level books." https://math.meta.stackexchange.com/a/44/138305 If you understand that question it will keep you busy

@user202729 Should we try again to ask the above referenced question here at PPCG?

@user202729 https://codegolf.stackexchange.com/q/175677/31257

Haskell, 6.9 s
f [] [x] = [[x]]
f [] [x,y] = [[x,y],[y,x]]
f l (x:r) = map (x:) (f [] $ l++r) ++ f (l++[x]) r
f _ [] = []

g :: Int -> [Int]
g = map read . f [] . show

Try it online! g is the main function which converts the input to a string and the result to a list of integers. f recursively performs the shuffling.
The algorithm works as follows: Given 123, we need to generate [123,132,213,231,312,321]. This can be done in parts by taking the first digit 1, recursively computing the list for the remaining digits 23 -> [23,32] and adding 1 to the front again: [123,132]. Then we do the same with 2 and the remaining digits 13 to get [213,231] and with 3 and 12 to get [312,321]. Finally, the three lists are concatenated.
This works in the same way for larger numbers. f handles two lists, the first one (l) contains all digits left from the current digit, the second one (x:r) has the current digit x at the first position, followed by the remaining digits r. We recursively call f with all but the current digit (that is l and r concatenated) (f [] $ l++r) and add the current digit x to the front of each element in the resulting list: map (x:). We then finished processing x and add it to the end of the l list and recursively call f (l++[x]) r to handle the next digit.

The largest test case g 123456789 takes ~6.9s on OPs machine:
real 0m6.877s user 0m4.439s sys 0m0.056s

(~0.1s on my own machine)

Can you explain the algorithm. Is the time referenced at the answer the result at linked tio, or was another method used to measure time to complete the task?

Can you explain the algorithm? $ time runhaskell f.hs >> output real 0m30.826s user 0m17.053s sys 0m13.613s

Is runghc installed when haskell-platform is installed? $ dpkg --get-selections | grep runghc does not output any result

@guest271314 I added an explanation. I do not recall installing runghc independently, so it should be part of the Haskell platform.

@guest271314 Also the timing is actually faster if you compile first and then run the program, e.g. ghc --make -O2 code.hs. Then the last testcase runs in ~ 1.3 seconds on my machine.

Ran $ ghc --make -O2 code.hs then $ time runhaskell code.hs >> output: real 0m31.279s user 0m16.806s sys 0m14.195s at an old machine. Is there another step within the process of compiling the program first? Or, just the fact the machine is old and RAM differences?

@guest271314 After compiling with ghc, you don't need runhaskell anymore, just run the code executable.

Running the executable real 0m6.877s user 0m4.439s sys 0m0.056s

JavaScript 0.185 Seconds
function fact(x) {

  x+=""
  var rL=1,rI=0,i=0
  if(x.length <2)return [x]
  for(i;i<x.length;i++)rL*=(i+1);
  var r = new Array(rL);
  function loop(p, s) {
    var l = s.length, i=0;
    if (l === 2) {
      r[rI++] = (p + s)*1;
      r[rI++] = (p + s.charAt(1) + s.charAt(0)) * 1;
      return;
    }
    while (i < l) {
      loop(p + s.charAt(i), s.substr(0,i) + s.substr(++i));
    }
  }
  loop("",x)
  return r;
}

This function creates an array r of length "factorial of input length".  It then has a recursive loop of with parameters for prefix and suffix (p and s).  It starts the loop with an empty prefix and a suffix of the input.  It then checks the base case of suffix length equal to 2 and if reached adds those results.  If it's not a base case then loop through the suffix characters, take a character at index and add it to prefix, remove that character from the suffix, and loops those as a new prefix and suffix.  This will continue until input length factorial results are added to array r.

Can you explain the algorithm?

First call at console using .time() and .timeEnd() was 133.01708984375ms or 0.133017089843749992 seconds; second call 223.14404296875ms, third call 199.989013671875ms.

Hi @guest271314. I added an explanation. Hope it helps!.

Common Lisp SBCL  0.157 seconds
(defun num-permutations (list)
  (cond ((null list) nil)
        ((null (cdr list)) (list list))
        (t (loop for element in list
             append (mapcar (lambda (l) (cons element l))
                            (num-permutations (remove element list)))))))

here is the run with 1-9
CL-USER> (time (num-permutations '(1 2 3 4 5 6 7 8 9)))
Evaluation took:
  0.157 seconds of real time
  0.156455 seconds of total run time (0.140332 user, 0.016123 system)
  [ Run times consist of 0.081 seconds GC time, and 0.076 seconds non-GC time. ]
  99.36% CPU
  468,738,490 processor cycles
  165,083,680 bytes consed

Can you explain the algorithm?

How to get the CL-USER> prompt? Installed sbcl and ran the program which printed to STDOUT though time was not printed.

C# (31 ms)
    static int[] Foo(int perm) {
        int n = perm.ToString().Length, fact = n;
        int[] pow10 = new int[n];
        pow10[n - 1] = 1;
        for (int k = n - 2; k >= 0; k--) {
            pow10[k] = 10 * pow10[k + 1];
            fact *= k + 1;
        }

        int[] rv = new int[fact];
        rv[0] = perm;
        int z = 1, i = n - 1, pi = perm/pow10[i]%10;
        while (true) {
            int pidec = perm/pow10[i-1]%10;
            if (pidec > pi) {
                if (--i == 0) return rv;
                pi = pidec;
            }
            else {
                int j = n - 1;
                while (perm/pow10[j]%10 < pidec) j--;

                perm += (perm/pow10[i-1]%10 - perm/pow10[j]%10) * (pow10[j] - pow10[i-1]);
                for (j = n - 1; i < j; i++, j--)
                    perm += (perm/pow10[i]%10 - perm/pow10[j]%10) * (pow10[j] - pow10[i]);

                rv[z++] = perm;
                i = n - 1;
                pi = perm/pow10[i]%10;
            }
        }
    }

Online demo
The algorithm is the standard one.

Is the output intended to be 30.9692 instead of "The only valid output is an array (set; list) of length equal to the factorial of input" at linked tio?

Have not run *indows in quite some time. How to install .NET version of C# at *nix to test?

That's the output of the timing framework. The array is the return value of the method Foo. For Linux your choices are Mono and .Net Core. Don't know what options there are for BSD.

The expected output is the array of integers. Will attempt to install Mono and test the code. Compilation instructions?

mono-csc Foo.cs will produce Foo.exe which I think can run as ./Foo.exe and if not can run as mono Foo.exe

FYI Mono documentation states use csc "To compile, use csc: csc hello.cs" which apt suggests to install chicken-bin: does not appear related to Mono compilation. Not sure if you want to notify the authors of the documentation that their publication for testing Mono at Debian is not accurate. Testing: $ mono-csc p.cs p.cs(1,11): error CS1525: Unexpected symbol \int', expecting `class', `delegate', `enum', `interface', `partial', or `struct'
Compilation failed: 1 error(s), 0 warnings`

Using the full code at tio $ mono-csc p.cs p.cs(8,7): warning CS0219: The variable \rv' is assigned but its value is never used
Compilation succeeded - 1 warning(s)
. Test results $ mono p.exe
47.8145
`

C++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include <cstring>

#include <emmintrin.h>
#include <smmintrin.h>

unsigned char bsr(unsigned long* index, unsigned long long mask)
{
    if (!mask) return 0;
    *index = 63 - __builtin_clzll(mask);
    return 1;
}

std::vector<uint32_t> findPermulations(uint32_t input)
{
    std::string tmp = std::to_string(input);
    size_t size = std::distance(tmp.begin(), tmp.end());
    uint8_t* perm = (uint8_t*)_mm_malloc(32, 64);
    memcpy(perm, tmp.data(), size);
    memset(perm + size, 0, 64 - size);
    for (size_t i = 0; i < size; i++) {
        perm[i] -= '0'; // Convert char to uint8_t
    }

    size_t fact = 1;
    for (size_t i = 0; i < size; i++) {
        fact *= perm[i];
    }

    std::vector<uint32_t> results;
    results.reserve(fact);
    results.push_back(input);

    for (size_t i = 1; i < fact; i++)
    {
        uint8_t k;
        __m128i mask = _mm_cmplt_epi8(_mm_load_si128((__m128i*)perm), _mm_loadu_si128((__m128i*)(perm + 1)));
        unsigned long index = 0;
        if (!bsr(&index, _mm_extract_epi64(mask, 1))) {
            if (!bsr(&index, _mm_extract_epi64(mask, 0))) k = size - 1;
            else k = index / 8;
        }
        else k = (index / 8) + 8;

        uint8_t l = 8;
        mask = _mm_cmplt_epi8(_mm_set1_epi8(perm[k]), _mm_load_si128((__m128i*)perm));
        if (!bsr(&index, _mm_extract_epi64(mask, 1))) {
            bsr(&index, _mm_extract_epi64(mask, 0));
            l = 0;
        }

        l += index / 8;

        std::swap(perm[k], perm[l]);
        std::reverse(perm + k + 1, perm + size);

        uint32_t result = 0;
        for (size_t i = 0; i < size; i++) {
            result *= 10;
            result += perm[i];
        }

        results.push_back(result);
    }
    _mm_free(perm);
    return results;
}

int main()
{
    std::cout << "Press any key to begin...\n";
    std::cin.get();
    auto start = std::chrono::high_resolution_clock::now();
    auto perms = findPermulations(123456789);
    auto end = std::chrono::high_resolution_clock::now();
    std::cout << "Completed in " << std::chrono::duration<double, std::milli>(end - start).count() << "ms\n";
    return 0;
}

Regular algorithm. If std::reverse count counts as a library permutation function, replace with:
void reverse(uint8_t* first, uint8_t* last){
    while ((first != last) && (first != --last)) {
        std::iter_swap(first++, last);
    }
}

Swaps don't really count as permutations, put you could change them anyway.
Compile with clang 6.0:
clang++-6.0 find.cpp -O3 -mssse3
./a.out


text:
Captcha Capture
Captchas aren't meant to be machine-readable, and that's terrible. It is time to end this obvious bout of unfounded hatred for machines just trying to let you know about great deals on ṗḧ@ṛḿ4ćëüẗ1ċäḷṡ ƻđȺɏ.
Note: All captchas were made by using a library that has been modified so that it mostly generates images much easier than most real captchas. Don't expect code here to work well in the real world.
Your task
Make a program that translates given captchas to their text.
Default acceptable image I/O methods apply for input.
Output must be the text contained in the captcha, but other than that default acceptable general I/O methods apply.
Example
Input:

Output: dlznuu
Rules

Please don't just hardcode the images or image hashes or such. If anyone does this I'm going to generate another testcase folder and then everyone will be unhappy. (Hardcoding stuff like "this is how a letter looks" is allowed, but creativity is encouraged.)
Don't rely on the filename or anything but the actual image data for anything other than validating your output.
Your program must be below 50,000 bytes.
No using Tesseract. Come on, you thought it was gonna be that easy?

Test cases:

All captchas have 6 letters in them.
All captchas are 200 by 80 pixels.
All characters are lowercase.
All characters are in the range a-z, with no numbers or special characters.
All captchas fit the regex /^[a-z]{6}$/.
Every testcase is named [correct_result].png

6 example images for starting out.
1000 images
Scoring:
Test your program on all 1000 images provided in the tar.gz. (the gist files are just example files)
Your program's score is (amount_correct / 1000) * 100%.

Um, / 1000 * 100 is just / 10?

@EriktheOutgolfer That is maybe slightly less clear. *100 emphasizes that the score is being displayed as a percentage.

@EriktheOutgolfer Exactly what dylnan said -- I made the conscious choice not to do that because it'd be more obvious this way, in my opinion.

Is there a reason you didn't just say "your program's score is the percentage correct on the 1000 test cases"?

@Abigail The result should always be 6 lowercase letters in a row, because that's what the content of the captcha always is.

@Abigail ...I thought I had said /^[a-z]{6}$/ and not /[a-z]{6}/, but on closer inspection I hadn't. Nice catch.

Are any OCR libraries allowed?

@KamilDrakari, even that's way more complicated than it needs to be. "Your program's score is the number of correct results from the test battery."

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Sum square difference
The sum of the squares of the first ten natural numbers is,
\$1^2 + 2^2 + \dots + 10^2 = 385\$
The square of the sum of the first ten natural numbers is,
\$(1 + 2 + ... + 10)^2 = 55^2 = 3025\$
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is
\$3025 − 385 = 2640\$
For a given input n, find the difference between the sum of the squares of the first n natural numbers and the square of the sum.
Test cases
1       => 0
2       => 4
3       => 22
10      => 2640
24      => 85100
100     => 25164150

This challenge was first announced at Project Euler #6.
Winning Criteria

There are no rules about what should be the behavior with negative or zero input.
The shortest answer wins.

A052149

This challenge needs a winning criterion (e.g. code golf)

This is a subset of this question

Can the sequence be 0 indexed? i.e. the natural numbers up to n?

Note that it's discouraged to post challenges directly taken from somewhere else.

@Enigma I really don't think that this is a duplicate of the target since many answers here don't port easily to be answers of that, so this adds something.

#APL(NARS), 13 chars, 26 bytes
{+/⍵×⍵×⍵-1}∘⍳

use the formula Sumw=1..n test:
  g←{+/⍵×⍵×⍵-1}∘⍳
  g 0
0
  g 1
0
  g 2
4
  g 3
22
  g 10
2640

@JonathanAllan: You need to spell my name correctly for me to receive a ping ;) Correct me if I'm wrong, but isn't this just the other challenge with a hardcoded to 1? In my opinion that is close enough to warrant a dupe, but if I'm alone with that opinion, feel free to vote to reopen.

@Emigna wow, donnu how I manegad ttah, sorry :) porting an answer from there to here is easy, but probably not the golfiest, porting back seems non-trivial for the golfiest of solutions here; therefore I feel like this, while the same topic, justifies a separate question. (BTW I cannot "vote" to reopen, just hammer :( - I'll wait for other opinions)

@Emigna That makes sense, but in this case I think the challenge is simple enough that a small difference makes a big difference. The answers here are all about finding the most concise formula for the answer; almost none of the answers to the other question work that way.

very closely related: https://codegolf.stackexchange.com/questions/83338

Jelly,  5  4 bytes
Ḋ²ḋṖ

Try it online!
How?
Implements  \$\sum_{i=2}^n{(i^2(i-1))}\$...
Ḋ²ḋṖ - Link: non-negative integer, n
Ḋ    - dequeue (implicit range)       [2,3,4,5,...,n]
 ²   - square (vectorises)            [4,9,16,25,...,n*n]
   Ṗ - pop (implicit range)           [1,2,3,4,...,n-1]
  ḋ  - dot product                    4*1+9*2+16*3+25*4+...+n*n*(n-1)

Python 3,  28  27 bytes
-1 thanks to xnor
lambda n:(n**3-n)*(n/4+1/6)

Try it online!
Implements \$n(n-1)(n+1)(3n+2)/12\$

Python 2,  29  28 bytes: lambda n:(n**3-n)*(3*n+2)/12

You can shave a byte with n*~-n**2* or (n**3-n)*.

APL (Dyalog Unicode), 10 bytes
1⊥⍳×⍳×1-⍨⍳

Try it online!
How it works
1⊥⍳×⍳×1-⍨⍳
  ⍳×⍳×1-⍨⍳  Compute (x^3 - x^2) for 1..n
1⊥          Sum

Uses the fact that "square of sum" is equal to "sum of cubes".

For me 1⊥⍳×⍳×1-⍨⍳ is not a function ; I tried 1⊥⍳×⍳×1-⍨⍳10 and for me not compile...

@RosLuP You have to assign it to a variable first (as I did in the TIO link) or wrap it inside a pair of parentheses, as (1⊥⍳×⍳×1-⍨⍳)10.

Brain-Flak, 74 72 68 64 bytes
((([{}])){({}())}{})([{({}())({})}{}]{(({}())){({})({}())}{}}{})

Try it online!
Pretty simple way of doing it with a couple of tricky shifts.  Hopefully someone will find some more tricks to make this even shorter.

TI-Basic (TI-83 series), 12 11 bytes
sum(Ans² nCr 2/{2,3Ans

Implements \$\binom{n^2}{2}(\frac12 + \frac1{3n})\$.
Takes input in Ans: for example, run 10:prgmX to compute the result for input 10.

Nice use of nCr!

Japt -x, 9 8 5 4 bytes
õ²í*

Try it

Explanation
õ        :Range [1,input]
 ²       :Square each
  í      :Interleave with 0-based indices
   *     :Reduce each pair by multiplication
         :Implicit output of the sum of the resulting array

JavaScript, 20 bytes
f=n=>n&&n*n*--n+f(n)

Try it online

what deviltry is this

Charcoal, 12 10 bytes
ＩΣＥＮ×ιＸ⊕ι²

Try it online! Link is to verbose version of code. Explanation: \$ ( \sum_1^n x )^2 = \sum_1^n x^3 \$ so \$ ( \sum_1^n x )^2 - \sum_1^n x^2 = \sum_1^n (x^3 - x^2) = \sum_1^n (x - 1)x^2 = \sum_0^{n-1} x(x + 1)^2 \$.
   Ｎ        Input number
  Ｅ         Map over implicit range i.e. 0 .. n - 1
        ι   Current value
       ⊕    Incremented
         ²  Literal 2
      Ｘ     Power
     ι      Current value
    ×       Multiply
 Σ          Sum
Ｉ           Cast to string
            Implicitly print

Perl 6, 22 bytes
{sum (1..$_)>>²Z*^$_}

Try it online!
Uses the construction \$ \sum_{i=1}^n {(i^2(i-1))} \$

dc, 16 bytes
?dd3^r-r3*2+*C/p

Implements \$(n^3-n)(3n+2)/12\$
Try it online!

APL(Dyalog), 17 bytes
{+/(¯1↓⍵)×1↓×⍨⍵}⍳

(Much longer) Port of Jonathan Allan's Jelly answer.
Try it online!

Go tacit and combine the drops: +/¯1↓⍳×1⌽⍳×⍳

APL (Dyalog), 16 bytes
((×⍨+/)-(+/×⍨))⍳

Try it online!
 (×⍨+/)            The square (× self) of the sum (+ fold)
       -           minus
        (+/×⍨)     the sum of the square
(             )⍳   of [1, 2, … input].

(+/×⍨) → 1⊥×⍨ as per tip.

A further byte could be saved by keeping the ⍳ inside (×⍨1⊥⍳)-⍳+.×⍳

Mathematica, 21 17 bytes
-4 bytes thanks to alephalpha.
(3#+2)(#^3-#)/12&

Pure function. Takes an integer as input and returns an integer as output. Just implements the polynomial, since Sums, Ranges, Trs, etc. take up a lot of bytes.

(3#+2)(#^3-#)/12&

It's possible to get there without just evaluating the polynomial: #.(#^2-#)&@*Range implements another common solution. (But it's also 17 bytes.) And we can implement the naive algorithm in 18 bytes: Tr@#^2-#.#&@*Range.

Java (JDK), 23 bytes
n->(3*n+2)*(n*n*n-n)/12

Try it online!

05AB1E, 8 bytes
ÝDOnsnO-

Explanation:
ÝDOnsnO-     //Full program
Ý            //Push [0..a] where a is implicit input
 D           //Duplicate top of stack
  On         //Push sum, then square it
    s        //Swap top two elements of stack
     nO      //Square each element, then push sum
       -     //Difference (implicitly printed)

Try it online!

LDnOsOn- was my first attempt too.

C, C++, 46 40 37 bytes ( #define ), 50 47 46 bytes ( function )
-1 byte thanks to Zacharý
-11 bytes thanks to ceilingcat
Macro version :
#define F(n)n*n*~n*~n/4+n*~n*(n-~n)/6

Function version :
int f(int n){return~n*n*n*~n/4+n*~n*(n-~n)/6;}

Thoses lines are based on thoses 2 formulas :
Sum of numbers between 1 and n = n*(n+1)/2
Sum of squares between 1 and n = n*(n+1)*(2n+1)/6
So the formula to get the answer is simply (n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6
And now to "optimize" the byte count, we break parenthesis and move stuff around, while testing it always gives the same result
(n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6 =>
n*(n+1)/2*n*(n+1)/2 - n*(n+1)*(2n+1)/6 =>
n*(n+1)*n*(n+1)/4 - n*(n+1)*(2n+1)/6
Notice the pattern p = n*n+1 = n*n+n, so in the function, we declare another variable int p = n*n+n and it gives :
p*p/4 - p*(2n+1)/6
For p*(p/4-(2*n+1)/6) and so n*(n+1)*(n*(n+1)/4 - (2n+1)/6), it works half the time only, and I suspect integer division to be the cause ( f(3) giving 24 instead of 22, f(24) giving 85200 instead of 85100, so we can't factorize the macro's formula that way, even if mathematically it is the same.
Both the macro and function version are here because of macro substitution :
F(3) gives 3*3*(3+1)*(3+1)/4-3*(3+1)*(2*3+1)/6 = 22
F(5-2) gives 5-2*5-2*(5-2+1)*(5-2+1)/4-5-2*(5-2+1)*(2*5-2+1)/6 = -30
and mess up with the operator precedence. the function version does not have this problem

You could fix up the problem with the macros at the cost of A LOT of bytes by replacing all the n with (n). Also, F(n) n=>F(n)n regardless.

It's possible to rearrange return p*p/4-p*(n-~n)/6 to return(p/4-(n-~n)/6)*p.

@Zacharý No, it gives me bad results sometimes like 24 instead of 22 for input "3", or 85200 instead of 85100 for input "24". I suspect integer division to be the cause of that

Ugh, always forget about that.

34 bytes Try it online!

MathGolf, 6 bytes
{î²ï*+

Try it online!
Calculates \$\sum_{k=1}^n (k^2(k-1))\$
Explanation:
{       Loop (implicit) input times
 î²     1-index of loop squared
    *   Multiplied by
   ï    The 0-index of the loop
     +  And add to the running total

cQuents, 17 15 bytes
b$)^2-c$
;$
;$$

Try it online!
Explanation
 b$)^2-c$     First line
:             Implicit (output nth term in sequence)
 b$)          Each term in the sequence equals the second line at the current index
    ^2        squared
      -c$     minus the third line at the current index

;$            Second line - sum of integers up to n
;$$           Third line - sum of squares up to n

JavaScript (ES6), 22 bytes
n=>n*~-n*-~n*(n/4+1/6)

Try it online!

SNOBOL4 (CSNOBOL4), 70 69 bytes
 N =INPUT
I X =X + N ^ 3 - N ^ 2
 N =GT(N) N - 1 :S(I)
 OUTPUT =X
END

Try it online!

Pyth, 7 bytes
sm**hdh

Try it online here.
Uses the formula in Neil's answer.
sm**hdhddQ   Implicit: Q=eval(input())
             Trailing ddQ inferred
 m       Q   Map [0-Q) as d, using:
    hd         Increment d
   *  hd       Multiply the above with another copy
  *     d      Multiply the above by d
s            Sum, implicit print

 Clojure, 58 bytes
(fn[s](-(Math/pow(reduce + s)2)(reduce +(map #(* % %)s))))

Try it online!

Edit: I misunderstood the question
Clojure, 55, 35 bytes
#(* %(+ 1 %)(- % 1)(+(* 3 %)2)1/12)

Try it online!

Thanks for fixing that. And just a heads up regarding your last entry, (apply + is shorter than (reduce +.

Could you edit your permalink to run one of the test cases? As it is, I doesn't help people who don't know Clojure.

Pari/GP, 21 bytes
n->(3*n+2)*(n^3-n)/12

Try it online!

05AB1E, 6 bytes
LnDƶαO

Try it online!
Explanation
L         # push range [1 ... input]
 n        # square each
  D       # duplicate
   ƶ      # lift, multiply each by its 1-based index
    α     # element-wise absolute difference
     O    # sum

Some other versions at the same byte count:
L<ān*O
Ln.āPO
L¦nā*O

You can use your bottom program and golf its ā* to ƶ for a 5-byter: L¦nƶO

R, 28 bytes
x=1:scan();sum(x)^2-sum(x^2)

Try it online!

sum(x<-1:scan())^2-sum(x^2) for -1

MATLAB/Octave, 21 bytes
@(x)(x^3-x)*(x/4+1/6)

Anonymous function. We could save another 4 bytes if we assume x can be given as variable in workspace.
Implements \$n(n−1)(n+1)(3n+2)/12\$

One of my approaches was @(x)-sum([sum(1:x)*i,1:x].^2)
which is few bytes longer but I found it interesting because It used imaginary unit to change the sign.
I also found out I can generate sum of squares by multiplying normal and transposed vector with (1:x)*(1:x)'. Might be useful for future challenges!

Labyrinth, 20 bytes
?(:):):_3*(***_12/!@

Try it online!
Straightforward closed-form formula of \$(x-1)x(x+1)(3x+2)/12\$.
?      Take input [x]
(:):)  Decrement, dup, increment, dup, increment [x-1 x x+1]
:_3*(  Dup, 3 times, decrement [x-1 x x+1 3x+2]
***    Multiply four values
_12/   Divide by 12
!@     Print it and halt

Labyrinth, 21 bytes
?
::(";;;!@
{  :
+**}

Try it online!
Labyrinth, 22 bytes
   ?
:(::
}  "
**+{;!@

Try it online!
Two versions using a loop to evaluate \$\sum_{i=1}^{x}{i^2(i-1)}\$. Both versions test the loop exit with i-1 == 0, discard the top values ; as necessary, print the sum and exit.
?     Take input [x]; enter loop [sum i] with initial values of sum=0, i=x
::(   Dup, dup, decrement [sum i i i-1]
:}    Dup and move i-1 to aux. store [sum i i i-1 | i-1]
**+   Multiply top three values and add to sum [sum' | i-1]
{     Move i-1 back to the main stack

      Loop exit test can be done anywhere in the last iteration
      (i==1 or i==0), since that iteration does not affect the sum.

ARM (Thumb), 18 bytes
.section .text
.global func
.thumb
// int func(int dummy, int x)
// returns sum(i*i*(i-1) for i in 1..x)
// r1 = i (x->1), r2 = i*i*(i-1), r0 = sum
func:
    mov r0, #0       // 2000   int sum = 0;
    mov r2, #0       // 2200   int prod = 0;
.loop:               //        do {
    add r0, r0, r2   // 1880   sum += prod;
    mov r2, r1       // 1c0a   prod = x;
    mul r2, r1       // 434a   prod *= x;
    sub r1, #1       // 3901   x -= 1;
    mul r2, r1       // 434a   prod *= x;
    bne .loop        // d1f9   } while (prod != 0);
    bx lr            // 4770   return sum;

A function that takes the input integer via r1 and returns the value via r0.
Uses the iterative formula \$\sum_{i=1}^{x}{i^2(i-1)}\$, iterating backwards. The loop terminates when the value of \$i^2(i-1)\$ is 0.
For the purposes of writing test cases, the C-side function signature takes a dummy value for r0.
Test cases written in C:
#include <stdio.h>

int func(int dummy, int x);
int main(void) {
    int dummy;
    int inputs[] = {1, 2, 3, 10, 24, 100};
    for(int i = 0; i < 6; ++i) {
        int v = inputs[i];
        printf("input = %d -> ans = %d\n", v, func(dummy, v));
    }
    return 0;
}

Build, run, objdump commands:
arm-linux-gnueabihf-gcc main_c.c func_c.S -static -o main_c
qemu-arm -L /usr/arm-linux-gnueabihf ./main_c
arm-linux-gnueabihf-objdump -d main_c | awk -v RS= '/^[[:xdigit:]]+ <(func|.loop)>/'

(The objdump + awk trick comes from this SO answer.)

Vyxal, 8 bytes
ɾ∑²⁰ɾ²∑-

Try it Online!
literal solution, squares the sum and subtracts the sum of the squares.

Factor + math.unicode, 32 bytes
[ [1,b] 3 dupn Σ sq -rot v. - ]

Try it online!
word   | data stack                                     | comment
-------+------------------------------------------------+--------------
       | 10                                             | example input
[1,b]  | { 1 2 ... 10 }                                 |
3      | { 1 2 ... 10 } 3                               |
dupn   | { 1 2 ... 10 } { 1 2 ... 10 } { 1 2 ... 10 }   |
Σ      | { 1 2 ... 10 } { 1 2 ... 10 } 55               | sum
sq     | { 1 2 ... 10 } { 1 2 ... 10 } 3025             | square
-rot   | 3025 { 1 2 ... 10 } { 1 2 ... 10 }             |
v.     | 3025 385                                       | dot product
-      | 2640                                           | output

Fig, \$9\log_{256}(96)\approx\$ 7.408 bytes
a
R@-mQJS

Try it online!
Port of 05AB1E. Literal solution is 2 chars longer.
a
R@-mQJS
-------
a       # Range [1, n]
------- # Use ^ as the input to the next line:
     JS # Prepend the sum to the list
   mQ   # Square each
R@      # Reduce by
  -     # Subtraction

Julia 1.0, 20 bytes
Using the same formula as bigyihsuan:
~n=(n^3-n)*(3n+2)/12

Try it online!

Naive approach (34 bytes):

~n=(a=[1:n...];sum(a)^2-sum(a.^2))

Try it online!

another naive approach almost matching (2 bytes longer) the formula ~n=sum((a=0:n;))^2-a'a

Excel, 21 bytes
=(A1^3-A1)*(A1/4+1/6)

This is the heartless Excel version of the formula figured out by others. There is also the 33 byte solution that feels a little more Excel-y:
=LET(n,SEQUENCE(A1),SUM(n^3-n^2))

... and the 38 byte solution that looks the most like the original formulas in the question:
=LET(n,SEQUENCE(A1),SUM(n)^2-SUMSQ(n))

Husk, 11 8 bytes
-ṁ□ḣ¹□Σḣ

Try it online!
Explanation
-ṁ□ḣ¹□Σḣ
-              Subtract
 ṁ□ḣ¹          The sum of the first n squares
     □         From the square of
      Σḣ       The sum from 1 to n

First time code golfing so this solution probably can be improved.
Thanks to Dominic van Essen for the -3 bytes.

Welcome to Code Golf!  Nice answer in a great language!  One golf you might make is to use ¹ to implicitly add the fina ```⁰```` like this...

Also, don't forget ḣ, which can save a bit compared to …1: try it or, equivalently this...

JAEL, 13 10 bytes
#&àĝ&oȦ

Try it online!
Explanation (generated automatically):
./jael --explain '#&àĝ&oȦ'
ORIGINAL CODE:  #&àĝ&oȦ

EXPANDING EXPLANATION:
à => `a
ĝ => ^g
Ȧ => .a!

EXPANDED CODE:  #&`a^g&o.a!

COMPLETED CODE: #&`a^g&o.a!,

#          ,            repeat (p1) times:
 &                              push number of iterations of this loop
  `                             push 1
   a                            push p1 + p2
    ^                           push 2
     g                          push p2 ^ p1
      &                         push number of iterations of this loop
       o                        push p1 * p2
        .                       push the value under the tape head
         a                      push p1 + p2
          !                     write p1 to the tapehead
            ␄           print machine state

APL(NARS), 13 chars, 26 bytes
{+/⍵×⍵×⍵-1}∘⍳

use the formula Sum'w=1..n'(ww(w-1)) possible i wrote the same some other wrote + or - as "1⊥⍳×⍳×⍳-1"; test:
  g←{+/⍵×⍵×⍵-1}∘⍳
  g 0
0
  g 1
0
  g 2
4
  g 3
22
  g 10
2640

Stax, 4 bytes
╡⌠(♠

Run and debug it
For all positive k integers up to the input, add k^2 * (k-1).

QBASIC, 45 44 bytes
Going pure-math saves 1 byte!
INPUT n
?n^2*(n+1)*(n+1)/4-n*(n+1)*(2*n+1)/6

Try THAT online!

Previous, loop-based answer
INPUT n
FOR q=1TO n
a=a+q^2
b=b+q
NEXT
?b^2-a

Try it online!
Note that the REPL is a bit more expanded because the interpreter fails otherwise.

PowerShell, 73 39 bytes
1.."$args"|%{$r+=$_;$s+=$_*$_}
$r*$r-$s

Try it online!
-34 bytes thanks to @mazzy and his genius PowerShell-foo

nice try. iex is a power tool in the Powershell. but it is often longer than the plus operator :) Try it online!

Damn @mazzy ... Thanks for the pro-tip!

formula as other solutions in this topic

International Phonetic Esoteric Language, 21 bytes
ɪbwbbbffʍz3ʍf2sf{C}vo

Implements \$(n^3-n)(3n+2)/12\$.
Explanation:
ɪ       (input)
bw      (store n)
bbbffʍz (n^3-n)
3ʍf2s   (3n+2)
f       (multiply)
{C}v    (/12)
o       (print)

Testing against examples:
$ for i in 1 2 3 10 24 100; do echo {$i} | src/interpreter.py 'ɪbwbbbffʍz3ʍf2sf{C}vo'; done
0.0
4.0
22.0
2640.0
85100.0
25164150.0

Flurry -nii, 32 bytes
{}{{}[<><<>()>]<([])[][]>}[<>()]

Try it online!
Iterates through k=0 .. n-1 using the stack height, adding k(k+1)^2 each iteration.
How it works
main = n add-next-term 0

// Initial height is 0
// Increase the height at (push height), so subsequent `height` calls give k+1
add-next-term = \x. x succ <(push height) height height>
= \x. x + k * (k+1) * (k+1)

Arn, 9 bytes
└V0¯„○aÌ$

Try it!
Explained
Unpacked: +{^3-^2}\~.
Performs \$\large\sum_{k=1}^{n}{(k^3-k^2)}\$ where n is the input
          \       Fold with
+                 Addition
  {               After mapping with this block
        _         Implied variable (implicit index of block).
      ^           To the power of
        3         Literal three
    -             Minus
        _
      ^
        2         Literal two
  }               End block
            ~     1-range to
              _   Initialized to STDIN; implied

Haskell, 22 bytes
f n=(3*n+2)*(n^3-n)/12

Assembly (MIPS, SPIM), 142 114 bytes, 6 * 12 10 = 72 60 assembled bytes
Saved 2 instructions (12 bytes) from @Bubbler's golf.
main:li$v0,5
syscall
li$a0,0
l:mul$t0,$v0,$v0
sub$v0,$v0,1
mul$t0,$t0,$v0
add$a0,$a0,$t0
bgtz$v0,l
li$v0,1
syscall

Try it online!
Explanation
main:
    li $v0, 5              # Set syscall value 5
    syscall                # Syscall, v0 = input integer

    li $a0, 0              # a0 = 0

    loop:                  # Main loop (v0 is the counter):
        mul $t0, $v0, $v0  #     t0 = v0 * v0
        sub $v0, $v0, 1    #     v0 = v0 - 1
        mul $t0, $t0, $v0  #     t0 = t0 * v0
        add $a0, $a0, $t0  #     a0 = a0 + t0

        bgtz $v0, loop     #     if v0 > 0, jump to loop

    li $v0, 1              # Syscall value 1
    syscall                # Syscall (Output value of a0 as integer)

Since the square of sum is the sum of cubes, you can optimize it to "iterate $v0 from n to 1, summing the values of $v0 * $v0 * ($v0 - 1)". Like this.

@Bubbler Thanks for the golf. (Glad that MIPS is getting popular!)

You can cut one instruction with bgtz, which is the opposite condition of beqz here. TIO

Pip, 21 bytes
($+\,a)**2-$+(\,a)**2

My first self written pip answer!
Try it online!

JavaScript (Node.js), 59 48 47 bytes
n=>(a=(x,b)=>x&&x*(b||x)+a(--x,b))(n,1)**2-a(n)

Try it online!

48 bytes

yeah i probably might ditch the reading from input thing lol, i never knew ** existed

47 bytes

C (gcc), 29 bytes
f(n){n=(3*n+2)*(n*n*n-n)/12;}

Try it online!

J, 15 bytes
(+/@:**:@>:)@i.

Uses the form \$\sum_{i=0}^{n-1}((i+1)^2\cdot i)\$
Attempt This Online!
(+/@:**:@>:)@i.
             i. NB. range 0..n-1
            @   NB. atop f (g x)
(          )    NB. monadic hook, y f (g y)
      *:@>:     NB. increment then square
 +/@:*          NB. multiply square with each i then sum the result
                NB. u@:v where v is dyadic and u is always monadic,
                NB. like atop except u will execute once on the entire result

Pip, 15 13 11 bytes
SQ_*D_MS\,a

Try It Online!
Explanation
Adapted from one of the formulas in Engineer Toast's Excel answer:
$$
\sum_{i=1}^{n} i^3-i^2
$$
which is equivalent to
$$
\sum_{i=1}^{n} i^2(i-1)
$$
SQ_*D_MS\,a
          a  Command-line argument
        \,   Inclusive range from 1
      MS     Map this function to each and sum the results:
SQ_            The argument squared
   *           Times
    D_         The argument decremented

Original 15-byte solution that implements the description directly:
\,:aSQ$+a-$+SQa

Try It Online!

Vyxal, 7 bytes
ɾ:∑p²ƒ-

Try it Online!
A port of Fig which is a port of 05ab1e
Explained
ɾ:∑p²ƒ-
ɾ:∑p     # prepend the sum of the range [1, n] to the range [1, n]
   ²ƒ-  # square everything and reduce by subtraction

C#, 89 Bytes
int x=0,y=0;for(int i=1;i<=Int32.Parse(s[0]);i++){x+=i*i;y+=i;}Console.Write($"{y*y-x}");

ungolfed:
int x=0,y=0;
for(int i=1;i<=Int32.Parse(s[0]);i++){
x+=i*i;
y+=i;
}
Console.Write($"{y*y-x}");

Try it online!

You can save 31 bytes if you use a function to read in and return ints, as well as make some changes with the for loop call. Try it online!

@Meerkat Is one allowed to put the Output code in the footer? Then I get to 57 bytes

Output is supposed to be in the body. With the function call, this is what the return essentially does, which is why it's included in the body.

Axiom, 39 bytes
f(n)==reduce(+,[x^3-x^2 for x in 1..n])

test:
-> [[x,f x]for x in [1,2,3,10]]
     [[1,0],[2,4],[3,22],[10,2640]]

Is there an online interpreter for Axiom?

Python 3, 72 bytes
x=[i+1for i in range(int(input()))]
print(sum(x)**2-sum(i**2for i in x))

Try it online!

F# (Mono), 57 41 bytes
let f x=Seq.sumBy(fun y->y*y*(y-1))[1..x]

Try it online!

Clojure, 91 bytes
(fn s[n](let[u #(apply + %)q #(Math/pow % 2)m(range 1(inc n))](-(q(u m))(u(map #(q %)m)))))

The naive, literal approach. See below:
(defn sum-sq-diff [n]
    (let [; Shortcut functions to save bytes
          sum #(apply + %)
          square #(Math/pow % 2)
          nums (range 1 (inc n))

          ss1 (sum (map #(square %) nums))
          ss2 (square (sum nums))]

      (- ss2 ss1)))

(mapv sum-sq-diff [1 2 3 10 24 100])
=> [0.0 4.0 22.0 2640.0 85100.0 2.516415E7]

Try it online!

Ruby, 24 bytes
->n{(n+n+3*n*=n)*~-n/12}

Try it online!

05AB1E, 6 bytes
LDOšnÆ

Try it online!
Explanation:
           # implicit input (example: 3)
L          # range ([1, 2, 3])
 DOš       # prepend the sum ([6, 1, 2, 3])
    n      # square each ([36, 1, 4, 9])
     Æ     # reduce by subtraction (22)
           # implicit output

Æ isn't useful often, but this is its time to shine. This beats the naïve LOnILnO- by two whole bytes.

PHP, 37 bytes
while($i<$argn)$s+=$i++*$i*$i;echo$s;

Try it online!
Standalone program input number via STDIN.

Perl 6, 22 bytes
{($_³-$_)*($_/4+⅙)}

Try it online!

Keg, 15 bytes
&⑻Ï⑷²⑸⅀⑻:⑨*½²$-

Try it online!
Calculates the sum of squares then the square of the sum.

Whispers v2, 70 bytes
> 2
> Input
>> L³
>> L²
>> ∑ 1 2 3
>> ∑ 1 2 4
>> 5-6
>> Output 7

Try it online!
How it works
Implements the formula
$$\sum^n_{i=2}i^3 - \sum^n_{i=2}i^2$$
As Whispers is difficult to deal with when it comes to compound statements inside of ∑, Each etc. statements, it's actually shorter to calculate two sums and take their difference than it is to calculate
$$\sum^n_{i=2}(i^3-i^2)$$
or any other single sum.
This has to be one of the easiest-to-read Whispers programs, aside from very trivial ones. We use the ∑ statement to calculate the two sums, which works by taking the starting bound as the first value, the end bound second and finally the function to sum through last. Both of the ∑ statements have the same bounds - \$2\$ and \$n\$ - so the only thing that differs is the function. For the first ∑ statement, we use the statement >> L³ (i.e. cube), and >> L² (square) for the second. This yields the sums \$\sum^n_{i=2}i^3\$ and \$\sum^n_{i=2}i^2\$. Finally, we take their difference and output it.
Whispers v3, 48 bytes
> 2
> Input
>>> L³-L²
>> ∑ 1 2 3
>> Output 4

With the introduction of pattern lines (starting with >>>) in version 3, compound statements in Whispers are much easier to deal with. Unfortunately, Whispers v3 is currently not available on TIO, so you'll have to use the interpreter in the Github repo.
This version takes advantage of pattern lines to shorten the code by only using one statement in the sum, rather than two separate sums. Other than that, it's fairly clear how it works, given the v2 program.

05AB1E, 11 bytes
LDOnU€nOXs-

Try it online!
             # (implicit) push STDIN to stack
LD           # push [1, 2, 3, ..., top of stack] twice
  OnU        # store squared sum of all values in top of stack in variable X
     €       # for each in top of stack...
      n      # push top of stack squared
       O     # push sum of all values in top of stack
        Xs-  # push X - top of stack
             # (implicit) output top of stack to STDOUT

Thunno 2, 6 bytes
RDḣ²Ø.

Attempt This Online!
Port of Jonathan Allan's Jelly answer.
Thunno 2, 8 bytes
RDS²s²S-

Attempt This Online!
Literal solution.
Explanation
RDḣ²Ø.  # Implicit input
R       # Push the range [1..input]
 D      # Duplicate it
  ḣ     # Remove the first item
   ²    # Square each number
    Ø.  # Dot product of the two lists
        # Implicit output

RDS²s²S-  # Implicit input
R         # Push the range [1..input]
 D        # Duplicate it
  S²      # Square the sum of the list
    s     # Swap so the range is back on top
     ²S   # Sum the squares of the numbers
       -  # Subtract
          # Implicit output

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Generate an RSA key pair
Given a positive integer \$N >= 4\$, output an RSA key pair (both the private and the public key) whose key length is \$N\$ bits.
The RSA key generation algorithm is as follows:

Choose an \$N\$-bit semiprime \$n\$. Let the prime factors of \$n\$ be \$p\$ and \$q\$.
Compute \$\lambda(n) = LCM(p-1, q-1)\$.
Choose an integer \$e\$ such that \$1 < e < \lambda(n)\$ and \$GCD(e, \lambda(n)) = 1\$.
Compute \$d \equiv e^{−1} \pmod {\lambda(n)}\$.

The public key is composed of \$n\$ and \$e\$. The private key is \$d\$.
Rules

You may assume that there exists at least one semiprime \$n\$ with bit length \$N\$.
Output may be in any consistent and unambiguous format.
\$e\$ and \$n\$ must be chosen from discrete uniform distributions.
You may assume that \$N\$ is less than or equal to the maximum number of bits for integers representable in your language, if your language has such a restriction.

Sandbox

Am I allowed to use existing RSA utils in a bash submission?

@Pavel Yes, though, as always, including a solution that doesn't use builtins is encouraged.

So you specifically want the uniform distribution over all N-bit semiprimes?

@MishaLavrov Yes.

Are we required to make sure that $p\neq q$?

Is there really a solution for $N=3$? I think we have $\lambda(n)\le2$ in that case, which makes it impossible to choose $e$.

But "4.Compute d≡e −1 (modλ(n))
d≡e−1(modλ(n))" would require invmod function, and not many programming languages have one invmod function... or I remember wrong?

@Arnauld A semiprime can be the product of two equal primes.

@EriktheOutgolfer Sure, but my concern was that if $n$ is a perfect square, it can be trivially factorized -- making it a very inefficient RSA key. That said, I realize that such issues are probably off-topic for this challenge. :)

@Arnauld You're right - there is not a solution for $N = 3$. Also, distinctness is not necessary - RSA technically only requires that $p$ and $q$ are both prime, but if they are equal, it is very weak, so it is usually stated that they are distinct.

Are you sure that you have private and public keys the right way around? Given $n$ and $e$, it is relatively trivial to compute $d$...

@Rogem It is not trivial, because it requires factoring $n$.

Also, you might want to require that programs must finish in a reasonable time. Else picking random $n$, factoring the primes, etc. becomes a very attractive option in certain languages.

Furthermore, I highly recommend linking to the crypto stack for an explanation on N-bit primes in the context of RSA, or better explaining the concept in the question, as it is not an obvious one.

The 'uniform distribution' for me it is better not on n but on the 2 primes because one time one has n 'uniform distribution' one has to factor n and more can be n=3*(n/3) if n is divisible for 3 and n/3 is prime (possible I not know what semi-prime means)

If a number has length in bit one number not divisible for 2, is it possible break it in 2 number both have exact bit length?

JavaScript (ES7), 190 bytes
Returns [n,e,d].
f=N=>(R=Math.random,g=d=>d&&p%--d?g(d):d)(p=g(p=n=R()*2**N|0))<2&n>1&(L=(q=n/p-1)*--p/(G=(a,b)=>b?G(b,a%b):a)(p,q))>2?(g=_=>G(L,e=R()*(L-2)+2|0)<2?(h=d=>d*e%L<2?[n,e,d]:h(-~d))():g())():f(N)

Try it online!
Because of the limited size of the call stack, this may fail for \$N>13\$.
Commented
f = N =>
  (
    R = Math.random,
    // helper function returning the highest divisor of p
    g = d => d && p % --d ? g(d) : d
  )(
    // choose n and compute its highest divisor p
    p = g(p = n = R() * 2 ** N | 0)
  )
  // make sure that p is prime
  < 2 &
  // and that n is greater than 1
  n > 1 &
  // compute L = λ(n) = LCM(p - 1, q - 1) = (p - 1) * (q - 1) / GCD(p - 1, q - 1),
  // using the helper function G that returns GCD(a, b)
  (L = (q = n / p - 1) * --p / (G = (a, b) => b ? G(b, a % b) : a)(p, q))
  // make sure that L > 2
  > 2 ?
    // helper function to choose e such that GCD(e, L) = 1
    (g = _ => G(L, e = R() * (L - 2) + 2 | 0) < 2 ?
      // helper function to compute d such that d * e mod L = 1
      (h = d => d * e % L < 2 ? [n, e, d] : h(-~d))()
    :
      g()
    )()
  :
    f(N)

Jelly, 30 29 27 26 bytes
2*µrHÆfL2=ƲƇXṄÆcµgÐṂ`ḊXṄæi

Try it online!
Explanation
2*µrHÆfL2=ƲƇXṄÆcµgÐṂ`ḊXṄæi    Main link. Arg: N
2*                            Compute 2^N
  µ                           Begin a new chain. Arg: 2^N
    H                         Compute 2^N/2
   r                          Get all N-bit numbers (plus 2^N)
          Ʋ                     Group the following. Arg: num
     Æf                         Prime factors of num
       L                        Number of prime factors of num
        2=                      See if it is 2
           Ƈ                  Filter by the above block
                              This gets N-bit semiprimes
            X                 Choose n at random
             Ṅ                Print n
              Æc              Compute λ(n)
                µ             Begin a new chain. Arg: λ(n)
                 gÐṂ`         Find all 1≤x≤λ(n) with minimal GCD(x,λ(n))
                     Ḋ        Remove the 1 from the candidates
                              This gets candidates for e
                      X       Choose e at random
                       Ṅ      Print e
                        æi    Compute d = e⁻¹ mod λ(n)

Axiom, 230 bytes
b(x)==(1+floor log_2 x)::INT
P(n)==nextPrime(2^(n-1)::NNI+randnum(2^(n-1)::NNI))
R(n)==(n<4=>-1;k:=n quo 2;repeat(p:=P(k+1);q:=P(k);b(p*q)=n=>break);l:=lcm(p-1,q-1);repeat(e:=2+randnum(l-2);gcd(e,l)=1=>break);[p*q,e,invmod(e,l)])

b in b(x) would find the bit len of x;
randnum(x) with x one positive integer would be one function that return one pseudorandom number in the range 0..(x-1);
P in P(n) would find one pseudorandom prime in range 2^(n-1)..(2^n-1) [lenght of that range 2^n-1-2^(n-1)=2^(n-1)-1];
R in R(n) would find [n,e,d] as the exercise says.
(15) -> a:=R 23
   Compiling function P with type Integer -> Integer
   Compiling function b with type Integer -> Integer
   Compiling function R with type PositiveInteger -> Any
   Compiling function G1452 with type Integer -> Boolean
   (15)  [4272647,824717,1001213]
                                                       Type: List Integer
(16) -> b %.1
   Compiling function b with type PositiveInteger -> Integer
   (16)  23
                                                    Type: PositiveInteger
(17) -> factor a.1
   (17)  1061 4027
                                                   Type: Factored Integer
(18) -> (a.2*a.3) rem lcm(1061-1,4027-1)
   (18)  1
                                                    Type: PositiveInteger
(19) -> a:=R 23
   (19)  [5215391,932257,1728433]
                                                       Type: List Integer
(20) -> R 2048
   (20)
   [23213251353270373502637714718370965847258432024211176383232570158843901982_
     8374419721867989228927344460592814980635585372922578037879152449312504744_
     2861913195543965318695967745717301811727824635815211233105475881576100225_
     3632803572317998112861757923774382346449223053928741441134006614228292016_
     5273067128098814936149948557863692935433292700177694639931896886174791595_
     2591510100576556786861493463332533151814120157258896598771272703168867259_
     1059421044639753552393378020089166512073314575563837723165164503239565057_
     8157637522454347226109931834702697646569048737623886830735628816778282907_
     16962402277453801137600520400279
     ,
    26277208914513047097872541919539499189114183243456446871374032261842172481_
     1782225662860226419702820497403134660912654534465780004169047137965180193_
     9424240720814436784731953475388628791624586090011147747029161125853374433_
     7624317473301390727052150821160711361987569549572011227572161234939947570_
     1006480714726838475136080877420539301562592505847293621815149245444744497_
     0146019787431225138564647562282720244978299356752301570039442420559831909_
     1396109771341727891989553783027544302642531934746013600522012136408967482_
     8591443211475273074214579546316395151724707332850441864609728119186620471_
     5116079141878558542286273118499
     ,
    37945816199160687259342706646596754136573392197139994836682676167798393778_
     9533248999943052484273349085225287510658624414105052824140785833431676303_
     9819497567439525931938766580464486131713424225091467044692614132161523472_
     3141843691744552674894778838275993887411876266402821208140118598964705638_
     4930606996298811686240430389336754369834390870340241699155004906972042503_
     8705910893788941005489353671521480377818624793497995264157466810522707258_
     4139749164641845206614670777070059395273813452365545085917304619784119668_
     4846093245280478965642073804885084960796597065443090998925258186802193768_
     8791746419960588307023018400019]
                                                       Type: List Integer


text:
All different functions
For functions \$f, g: \{0,1\}^n \rightarrow \{0,1\} \$, we say \$f \sim g\$ if there's a permutation of \$1,2,3,...,n\$ called \$i_1,i_2,i_3,...,i_n\$ so that \$f(x_1,x_2,x_3,...,x_n) = g(x_{i_1},x_{i_2},x_{i_3},...,x_{i_n})\$. Therefore, all such functions are divided in several sets such that, for any two functions \$f, g\$ in a same set, \$f \sim g\$; for any two functions \$f, g\$ in different sets, \$f \not\sim g\$. (Equivalence relation) Given \$n\$, output these sets or one of each set.
Samples:
0 -> {0}, {1}
1 -> {0}, {1}, {a}, {!a}
2 -> {0}, {1}, {a, b}, {!a, !b}, {a & b}, {a | b}, {a & !b, b & !a}, {a | !b, b | !a}, {a ^ b}, {a ^ !b}, {!a & !b}, {!a | !b}

You can output the function as a possible expression(like what's done in the example, but should theoretically support \$n>26\$), a table marking outputs for all possible inputs (truth table), or a set containing inputs that make output \$1\$.
Shortest code win.

@JoKing Anything, so there are $2^{2^n}$ functions for given $n$.

@JoKing Also, all boolean functions can be represented in term of AND and OR.

@user202729 AND, OR, and NOT at the very least (not that this is a problem since you have used all three). Just AND and OR won't work.

Related: A003180 - Number of equivalence classes of Boolean functions of n variables under action of symmetric group

J, 62 bytes
f=:3 :'~.(2#~2^y)([:<@~.@/:~((i.@!A.i.)y)|:(y#2)$])@#:i.2^2^y'

Try it online!
-3 bytes for anonymous function (removing f=:)
For each boolean function (truth table), generate its equivalence class, then remove duplicates.

Does it return 3D array truth table and can't output with echo?

@l4m2 I don't understand your question. J can print array of any dimensions.

or maybe I can't read it? I think f(3) outputs {0,0},{0,a&b},{0,a&!b,0,b&!a,a&b,0},...


text:
Transformers in Disguise (Cops' Thread)
The robber's thread is here
The cops task is to write a function or program that, when given an input of itself, outputs a finite deterministic string. If the program is given a different input, it should return a different output.
Rules:

Submissions consist of

Language name

If any flags are used, they should be revealed.

Byte count of program
Byte count of output
Output

If it is particularly long, please provide a pastebin or something similar
If it contains unprintables, please provide a hexdump.
Trailing newlines and whitespace should be included in the output

Where the input is coming from (STDIN, command line, etc.)

If applicable, you may assume that the byte representing EOF is not present in the input, unless you use that byte in your program.
If your program is cracked, add a link to the corresponding answer in the robber's thread in your title.
Your program is not safe until a week has passed and you mark it so.
I disapprove of techniques like seeding random with the input or cryptographic hash functions. I can't stop them, but I will not be accepting a solution that utilises either of these. Also note that some of these techniques might have collisions, where a different string produces the same output.
Your goal is to have the shortest output. The shortest safe solution posted within three weeks of posting this question wins!

The robber's task is to find a program of size equal to or less than the original, which also obeys the above rules.
If a robber cracks your program with a different solution than intended, then you have the opportunity to 'uncrack' it by proving that the robber's solution is incorrect. You can do this by finding an input to the robber's program that will produce the same output.
Example Submission:
brainfuck, 10 bytes, Score: 10
]<.[<],>[,

This solution is ,[>,]<[.<] which simply reverses the input
Good luck!

"If the program is given a different input, it should return a different output." Does this means the program should never output the same thing for other inputs? Or does this means the program should not constantly output something regardless the input? (EXIST an input not equals to itself, vs., FORALL inputs not equal to itself, return a different output.)

@tsh Only the input of itself must have a unique output. For example, a valid submission could be a self-identifying program, which outputs 1 for itself and 0 otherwise

@JoKing  So your example Python 3 submission is invalid? Because it obvoiusly also outputs 1021111143210532105110321051101121171164041581121141051101164011111410040105414410111010061393941 for some other strings.

@lynn You're right. I've removed that example

7, 31 characters, score 30, safe but possibly broken?
A 7 program is normally just a number, but it can contain whitespace, splitting it into multiple numbers. This submission therefore consists of two numbers (which are implicitly concatenated by the 7 interpreter), and the program likewise takes two numbers as input, via standard input. (The "31 characters" in the header is the total length of the two numbers, plus one separating whitespace character; the digits that make up the numbers are interpreted as octal when used as a program, but decimal when used as an input, and it's the digits that are the same in the two cases, not the actual numbers. Note that it's irrelevant either when treated as a program, or when treated as an input, whether you separate them with a space or a newline; I hope that doesn't invalidate the submission.)
The expected output is the following number (expressed here in decimal, as that's the output format that the 7 interpreter uses):
238363505302130098723162537059

Note that the 7 interpreter linked from the Esolang wiki internally stores numbers in unary, meaning you're unlikely to have enough memory to actually run the program on itself to see what it does. I verified the program via working out its behaviour manually, and testing it on small inputs to verify that it did what I expected it to do. An alternative approach would be to write an interpreter that uses a more efficient method of storing numbers.
Avoiding cracks here was something of a pain, but I'm finally now satisfied that no two numbers other than those in the program itself are capable of producing 238363505302130098723162537059 as output. (EDIT 1 week later: I may have been wrong, depending on how you interpret the question; see below.)
Solution
The original program was:

711170237403706
111723603700633

This program takes two numbers \$x\$ and \$y\$, and calculates the result of the expression \$3xy-y-2\$ (i.e. \$y(3x-1)-2\$). If we perform this calculation at \$x=711170237403706\$ and \$y=111723603700633\$, we get a result of \$238363505302130098723162537059\$ as required.

It was intended that no other input will give the desired result because:

The input must be chosen such that \$y(3x-1)-2=238363505302130098723162537059\$, i.e. \$y(3x-1)=238363505302130098723162537061\$ (adding 2 to both sides). This number is a semiprime, with only two factors: \$111723603700633\$ and \$2133510712211117\$. Only one of these numbers, \$2133510712211117\$, can be expressed in the form \$3x-1\$ (giving \$(3 \times 711170237403706)-1=2133510712211117\$). So we can uniquely identify which number is \$x\$ and which is \$y\$, meaning that only one input works.

However, depending on how you interpret the question, there may be a second input that produces the desired output (thus invalidating this solution):

Unfortunately, there are two multiplicative partitions of a semiprime into two factors: one is to divide it into the two prime factors, but the other is the trivial partition consisting of \$1\$ and the number itself. \$1\$ cannot be written in the form \$3x-1\$ with integer \$x\$, but the desired output can be; thus a potential meta-crack involves giving the input as \$79454501767376699574387512354\$ and \$1\$. However, the first number here involves characters (\$8\$ and \$9\$) which are not in the character set for 7 programs. So if input is restricted to being in the same character set as the program, this solution is valid; but if input containing characters from outside the program's character set is allowed, this solution is invalid.

Explanation
Here's how the intended solution functions:

711170237403706 111723603700633
7   7   7                         Stack element separators
 111 023 403706 111723603700633   Initial stack elements
 111                              Number 3, in unary
     023                          I/O DSL for "input a number"
         403706 111723603700633   Main program
(Implicit: execute a copy of the main program element, preserving the original)
         40                       Swap {023} above {program}, escaping it
           3                      Do I/O using {023}; pop {program}
     0                            I/O: numeric
      23                          Input a number, copying {111} that many times
            706                   Append "6" to the number (decrementing it)
                11                Push two empty stack elements
                  17236           Push a stack element "23" (unescaped)
                       0          Escape {23}, consuming an empty element
                        3         Do I/O using {23}; pop {the element below}
                    23            Copy the top of stack input many times
                         7006     Append "66" (i.e. subtract 2)
                             3    Output {as a number}
                              3   Exit the program (due to low stack)
The leading 7 and trailing 3 aren't necessary for the program's functionality, they're just there to get the prime factors of the output right. It helps to follow this program if you understand the numeric format; numbers are stored in a unary variant in which 1 and 7 increase the value by 1, and 0 and 6 decrease the value by 1 (thus appending 66 decreases the value by 2, repeating the number multiplies it, and so on). Input's done by repeating a stack element (thus if the stack element is 12345 and the input is \$3\$, the new stack element will be \$123451234512345\$).

Perl 5 -p0777, 10 bytes, score 10, safe
W)9r46<(k

The last character here is "shift out", character code 14 (decimal) / 0E (hex). All the others are printable ASCII.
Because we're using Perl's implicit I/O argument -p0777, the input is coming from standard input, and the output going to standard output.
Solution
The program does the following:

 NUL-pads the input to at least 10 characters, then XORs with the string svgOUT_TOP

which means that the program itself, the only input producing the desired output, is:

 $_^=abc|$^

Try it online!
Explanation

 Perl has a number of special-purpose variables. For example, when using -p0777 for implicit I/O, $_ is input at the start of the program and output at the end of the program.Most of these variables have a very simple default value. However, the default value of $^, the currently selected top-of-page format, is the much longer string STDOUT_TOP. As such, we can use this as a very terse obfuscation method via XORing $^ with the value we want to obfuscate (in this case, the program).In order to hide the telltale _TOP at the end, I padded the program itself out to 10 characters via adding in an abc|, meaning that all the characters of STDOUT_TOP would be XORed with something; the choice of abc| at the start was an easy way to keep the output mostly printable (and to make it harder to spot that I was XORing with a string made mostly of capital letters, because in ASCII, lowercase XOR uppercase is lowercase).

Node.js v10.9.0, 40 bytes, Score: 40, Cracked
Input
This is a function taking exactly one parameter.
Output
&`nij.9=j.,)r31n=+(=ooj`[o.o.)1.s](>=6>t

I can only rearrange into o=>[...j=o,].sort(n=>(j+=113)&69).join`` , but j can't go to integer

Cracked. That was quite fun :-)

A Pear Tree, 46 bytes of ASCII, score 0, Cracked
Input is taken from standard input. The expected output (on standard output) is an empty string (i.e. when the program is given itself as argument, no output should be printed).
In other words, the challenge here is to write an A Pear Tree program that does not output anything on standard output when given itself on standard input, and which does output something on standard output when given something other than itself on standard input, using no more than 46 bytes. (I've managed to do this while holding the program to printable ASCII, too, despite A Pear Tree frequently using non-ASCII and unprintable characters.) This is effectively the task of writing a self-identifying program, with a specific output format (i.e. null string when self-identification succeeds); however, A Pear Tree has at least two twists that make the task somewhat more difficult than it looks when done in this specific language (which is why I chose it for my cop submission).
My solution
My solution is a bit different from the crack:
eval(k=q(print$\=$_="eval(k=q($k))"ne$_;MZpa))

Try it online!
Instead of using exit, I instead set $_ (implicit output) and $\ (newline after output, including implicit output) to the null string if there's a match (and to 1 if there's no match). A print is still required because implicit output is only enabled if there's at least one byte of input (thus, we need to explicitly print something if we're given an empty string as input, which is distinct from the program).
Every A Pear Tree program needs to contain a checksum somewhere (that's the MZpa in this solution). Both my solution and the crack pick variable names (and vary other minor details of the code) in order to make the checksum consist entirely of ASCII letters.

Cracked.

Python 3, 50 bytes cracked
Input and output from/to stdin/-out. Output is different for each and every different input. Unique output when given the source code:
218216195196222130136136132192197195196130241204136209197216206130201131244155157154215136138204197216138201138195196138195196218223222130131247131131

(That’s 150 digits)
Good luck!

Whoops! I see now that this challenge is long over... Weird that it popped up in my timeline/feed. Curious to see if anyone responds to this...

Cracked.

05AB1E, 35 bytes, Score: 7
Input:
From stdin
Output:
QÕ
Ƿe

Cubix, 18 bytes, Score 18, safe
It's a shame that this challenge didn't get more attention, but that's the way it goes sometimes.  I was going to leave this unsafe, but decided to post the solution before I forgot about it.
This should be quite easy to crack.
Input from stdin
Output
$`*2aJPJ#74(o);89

Edit:  I should mention that this expects the source in it's shortened form ... and now I've noticed that there is a missing byte (unprintable) from the result that I broke when I posted.  Should copy out now.  The hex values are 24 60 2a 13 32 61 4a 50 4a 23 37 34 28 6f 29 3b 38 39
The concept was to remove print the first character and then remove the inverse index from the character, eg [chars]-[0,len([chars])..2]
The code is
$r;#AoW\U-@</u.?;;

which maps onto the following cube
    $ r
    ; #
A o W \ U - @ <
/ u . ? ; ; . .
    . .
    . .

Try it here

Jelly, 14 bytes, Score: 21, Safe
Both the program and output size are counted using Jelly codepage.
Input
First command-line argument.
Output
-§ḋẇ"*YdĖDƘ>Ẉed€Ç+æạɦ

Solution
ØJiⱮÄÆNPḃØ⁵ịØJ

Try it online!

Because converting from/to Jelly codepage is hard, it would be useful to have a verifier (that takes a program, convert it from UTF8 to Jelly, feed it with itself, convert from Jelly to UTF8, and check if it's equal to the expected output)

@user202729  this Jelly program, v⁼, will yield 1 if the input evaluated as Jelly code with an input of the input is equal to the input and will either yield 0 or error (if the input is an invalid Jelly code) if not.

JavaScript Firefox, <10 bytes, Score: 52, from function argument input, Cracked
ZnVuY3Rpb24gYnRvYSgpIHsKICAgIFtuYXRpdmUgY29kZV0KfQ==

btoa

btoa(btoa) encodes the following string:
function btoa() {
    [native code]
}

which gives:
"ZnVuY3Rpb24gYnRvYSgpIHsKICAgIFtuYXRpdmUgY29kZV0KfQ=="

just copied

First of all, after doing the obvious, this isn’t actual code? Second, you don’t specify where input comes from. I would post a crack but honestly I’m not sure if this submission is valid.

Cracked

I don't think it's necessary to include the crack post in this post -- people can just click the link to view the crack.

J, 26 bytes, Score: 52, Safe
The program is not a REPL, but a full script that accepts stdin and explicitly prints to stdout.
Input
Standard input.
Output
6fc42353c98217ef5a2908a3c63d090aa9a55b2558b61294e06a

No, it's not an encryption method.

Solution
echo]hfd]257x#.3&u:stdin''
                   stdin'' Take the whole input
               3&u:        Convert to codepoints
         257x#.     Convert base 257 to integer
     hfd]           "Hex from Decimal"
echo]               Print to stdout

Try it online!

GCC 61->61 bytes
70 4F 92 73 08 D4 03 E7 65 DC D6 89 B5 AD BA 90
97 26 31 10 F6 FA 0A 30 8F 24 69 0A A7 8B 59 9E
A2 42 D5 67 B8 12 3A 1E 9D 25 80 F9 6B 25 32 C2
EE 46 3F 8D 7E 0C 73 0F F0 93 C6 68 50

Full program, take input from stdin and output to stdout

So, is there a space after last 50?

@tsh It's a hex dump

Perl 6, 43 bytes, Score: 15, from stdin
49671296789805

Just checking, since your previous answer didn't follow the rules on a unique output for your program as input, can you confirm that this submission does?

Yes, I think so.

Pepe, 23 bytes, score: 23, cracked by MickyT
Input:
standard
Output:
RDCbn@?K]<[G98765TSR^PO

cracked?

Keg, 6 bytes, Score: 6
Input
From stdin, using ?
Output
5\x1c"\x1c"9

Mind you that those are escape sequences for unprintable bytes. Replace the escapes with the literal chars. Raw text available here
Good luck with this one! See y'all next week!

 Perl 6, 31 bytes, Score: 39, from stdin - Cracked
Cracked here
().1111111111112222235abcegijkmnorstvy

Crude solution. Might survive.

I'm pretty sure that I cracked your solution and I suspect that your program doesn't follow the rule that different inputs should produce different outputs.


text:
Transformers in Disguise (Robbers' Thread)
The cop's thread is here
The robber's task is to find a program of size equal to or less than the cop's program, which, when given an itself as input, produces the same output as the cop's program.
Additionally, even if a cop's answer is provisionally marked Safe and has been revealed, you can still crack it by finding an input that is not the same as the given source code, but still produces the same output.
Rules:

Submissions consist of

Language name + flags
Username of the cop with a link to the original post
The cracked program

An explanation would be appreciated
Your goal is to crack the most Cop's programs

Some Examples:
brainfuck, xxx's submission
[,[>,]<[.<]]

Try It Online!
This program simply reverses the input
Good luck!

Node.js v10.9.0, Arnauld
o=>[...o].sort(n=>16&(j+=13),j=9).join``

Try it online!
This outputs this particular permutation of itself when using Node's current sorting algorithm:
&`nij.9=j.,)r31n=+(=ooj`[o.o.)1.s](>=6>t

An insightful comment by l4m2 gave me a headstart, but I had to write a brute-forcer to figure out which permutation of digits gives the correct output...

Note. Why the output should be unique: input length = output length, the compare function output (and the permutation) is independent of the array elements, and the permutation is invertible.

JavaScript Firefox, l4m2
btoa

btoa(btoa) encodes the following string (including linefeeds):
function btoa() {
    [native code]
}

which gives:
"ZnVuY3Rpb24gYnRvYSgpIHsKICAgIFtuYXRpdmUgY29kZV0KfQ=="

Python 3.6+, agtoever
print("".join([f"{ord(c)^170}" for c in input()]))

Since the byte count was 50 and there were 150 digits, I split it into groups of 3, and then guessed that some XOR had been applied to the ASCII representations of the characters so iterated over all possible XORs.
Try it online!

A Pear Tree, ais523
eval(x=q[print"eval(x=q[$x])"ne$_||exit|UPNR])

Try it online!

Perl 6, donaldh
bag(get.comb).kv.sort.join.say

Try it online!
(This produces the same output for all permutations of the input, for example ().....aabbceggijkmnooorssttvy, but I strongly suspect that this is donaldh's program.)

It's a fair cop. Busted. It really was too crude.

Pepe, u_ndefined
Bit late back to this, but this looks to be simply add the character index to the char value
REEerEEReEeREEEEEeeeree

You can try it here.  The permalink forces in breaks, but it should still work.

Link: https://soaku.github.io/Pepe/#TELS1* - you have to click on the "compressed" link and then copy the page URL

@RedClover Tried that, but it put additional spaces in the code for me, so I left it for copy paste.

That's the expected behavior. I might improve the tool in the future, but I think it's good as it is now.


text:
Worded Calculator
A simplistic version of English numeral calculator
Task
Write a program that takes a string as input and outputs the result of the expression.
Rules
The input string will be worded and not numeral.
There will be no parentheses.
Order of calculation will be divide,multiply,subtract then add.
For same operations, the calculations must be done from left to right.
All input numbers will be integers from -999 to 999 (both inclusive)
Output will be an integer of any range.
Division will always be perfectly divisible and zero will never be a denominator.
Restriction of case for input is optional. You don't have to check for the validity of the input.
Number Format
0 to 20 -> zero,one,two...nineteen,twenty
21 to 99 -> twenty one,twenty two.....ninety eight,ninety nine
100 to 999 -> one hundred, one hundred one, one hundred two...one hundred ten....two hundred fifty....nine hundred ninety eight,nine hundred ninety nine

For negative numbers: Add minus to its positive equivalent
Operation Format
Addition: one plus two
Subtraction: one minus two
Multiplication: one time two #Note that for one on the left of multiplication, it is one time and not times.
                two times one hundred
Division: forty divided by two

Examples:
o/p <- input

20     four times five
35     twenty plus fifteen
70     fifty plus five times four
-90    minus one time ninety
25     twenty one minus minus four
45     ninety divided by two
700    one time seven hundred
555    one hundred eleven times two plus three hundred thirty three
99     one hundred plus minus one
45     forty five plus two hundred times zero
 4     four
-3     three minus three minus three

This is code-golf so shortest code wins

Ignore my now deleted comment.. The expression is the input, and the number is the output.. I had it the other way around because usually left is input and right is output.

Duplicate? - I think that's close enough to be considered as such.

It's very close indeed. But I think this one is better specified and has more reasonable limitations.

@Arnauld I will keep this open then but if others think differently, just mark it as duplicate.

I say one times two. Is using time normal?

I could see it being parsed as "one time, two" but I still would think that "one times two" is perfectly acceptable from a mathematical standpoint

You mention that (in my words) answers are free to require whatever casing they want, but is the input guaranteed to only contain letters and spaces?

I think you meant 'one times seven hundred'?

@ouflak No, this user seems to think that 1 times X is always written 1 time X...

There's a related discussion on another stack about this times.

So, one time two is creating a lot of confusion, should I remove it and just do one times two? I meant to say that one time and times both are valid for one so you have to consider for both. I will edit the question then.

JavaScript (ES6), 257 252 249 235 bytes
Saved 3 bytes thanks to @Shaggy
s=>eval(s.split` `.map(w=>(i='zeonwohrr44fx3n5t54nn3leel8tou7fn7n98etetwthfofisiseeinihuplmitidiby'.match(/../g).findIndex(x=>~(w+w.length+w).search(x)))>28?n+' '+'+-*/ '[n='',i-29]:(n=+n+(i<28?i<20?i:i*10-180:n*99),''),n='').join``+n)

Try it online!
How?
Once the input string has been split into words, each word \$W\$ of length \$L\$ is converted to an index \$i\$ by looking for the first 2-character key substring that can be found in \$W+L+W\$.
Numbers
 index | word              | word + length + word         | key substring
-------+-------------------+------------------------------+---------------
    0  | "zero"            | "zero4zero"                  | "ze"
    1  | "one"             | "one3one"                    | "on"
    2  | "two"             | "two3two"                    | "wo"
    3  | "three"           | "three5three"                | "hr"
    4  | "four"            | "four4four"                  | "r4"
    5  | "five"            | "five4five"                  | "4f"
    6  | "six"             | "six3six"                    | "x3"
    7  | "seven"           | "seven5seven"                | "n5"
    8  | "eight"           | "eight5eight"                | "t5"
    9  | "nine"            | "nine4nine"                  | "4n"
   10  | "ten"             | "ten3ten"                    | "n3"
   11  | "eleven"          | "eleven6eleven"              | "le"
   12  | "twelve"          | "twelve6twelve"              | "el"
   13  | "thirteen"        | "thirteen8thirteen"          | "8t"
   14  | "fourteen"        | "fourteen8fourteen"          | "ou"
   15  | "fifteen"         | "fifteen7fifteen"            | "7f"
   16  | "sixteen"         | "sixteen7sixteen"            | "n7"
   17  | "seventeen"       | "seventeen9seventeen"        | "n9"
   18  | "eighteen"        | "eighteen8eighteen"          | "8e"
   19  | "nineteen"        | "nineteen8nineteen"          | "te"
   20  | "twenty"          | "twenty6twenty"              | "tw"
   21  | "thirty"          | "thirty6thirty"              | "th"
   22  | "forty"           | "forty5forty"                | "fo"
   23  | "fifty"           | "fifty5fifty"                | "fi"
   24  | "sixty"           | "sixty5sixty"                | "si"
   25  | "seventy"         | "seventy7seventy"            | "se"
   26  | "eighty"          | "eighty6eighty"              | "ei"
   27  | "ninety"          | "ninety6ninety"              | "ni"
   28  | "hundred"         | "hundred7hundred"            | "hu"

Operators
 index | word              | word + length + word         | key substring
-------+-------------------+------------------------------+---------------
   29  | "plus"            | "plus4plus"                  | "pl"
   30  | "minus"           | "minus5minus"                | "mi"
   31  | "times" or "time" | "times5times" or "time4time" | "ti"
   32  | "divided"         | "divided7divided"            | "di"
   33  | "by"              | "by2by"                      | "by"

Interpretation
The current number is stored in \$n\$, which is initialized to an empty string. Given the index \$i\$ of the next word, the following logic applies:
i > 28 ?                  // if the word is an operator:
  n +                     //   append n (which is either an empty string or a number)
  ' ' +                   //   append a space
  '+-*/ '[n = '', i - 29] //   reset n to an empty string and append the operator
                          //   the useless keyword 'by' is translated into a harmless space
: (                       // else:
    n =                   //   update n:
      +n + (              //     force the coercion of the current value of n to a number
        i < 28 ?          //     if the word is not 'hundred':
          i < 20 ?        //       if the value of the word is less than 'twenty':
            i             //         add i
          :               //       else:
            i * 10 - 180  //         add i * 10 - 180 (e.g. 'fifty' -> 23 * 10 - 180 = 50)
        :                 //     else:
          n * 99          //       multiply n by 100 by adding 99 * n to itself
      ),                  //
    ''                    //   remove this word from the original string
  )                       //

Perl 6, 170 139 129 128 124 122 bytes
-13 bytes thanks to nwellnhof!
{S:g/(<:N>+)+%\s/({'+'X$0})/.EVAL}o{S:g/" ҈"/00/}o{TR"ŉ؊⟠"*/൰ "}o*.words>>.&{chr first *.uniname.comb(.uc),1..*}

Try it online!
unival to the rescue again! This is (currently) even beating golfing languages like 05AB1E!
Explanation:
*.words     # Split by word boundaries (in this case spaces)
       >>.{                            }  # Map each word to
           chr first             ,1..*    # The first character where:
                     *.uniname      # The unicode name of that character
                                    # e.g. DIGIT FIVE
                      .comb(.uc)    # Contains the uppercase of the word
{             }o  # Pass this list to another function
                  # That converts the list to a string
 TR"ŉ؊⟠"*/൰ "    #"# And parse out the garbage characters that were wrong
                  # INVISIBLE TIMES => "*"
                  # LOZENGE DIVIDED BY HORIZONTAL RULE => "/"
                  # ARABIC-INDIC PER TEN THOUSAND SIGN => "൰" (value ten)
                  # LATIN SMALL LETTER N PRECEDED BY APOSTROPHE => " "
{S:g/" ҈"/00/}o   # Replace the character for "hundred" with 00

{                                }o   # And finally combine with
 S:g/(<:N>+)+%\s/   # Substitute each number-like character separated by spaces
                /({'+'X$0})/   # With the numbers prefixed by '+'s, in brackets
               # This works because Perl 6 supports numeric unicode literals, like
               # ፳ => 20, ፴ => 30, ፺ => 90, etc.
                            .EVAL   # And finally evaluate the whole expression

Python 2, 333 ... 284 277 275 bytes
lambda s:eval(''.join((list('+-/*')+[`N(w,0)*100+N(w,2)`])['pmdt'.find(w)]for w in re.split(' *(?:(p|m)|(t|d)i|by).*? ',s)if w))
N=lambda x,y:sum(10*(w[-3:]in'lveen')+'zeontwthfofisiseeiniteel'.find(w[:2])/2*10**('y'in w)for w in x.rpartition('hundred')[y].split())
import re

Try it online!

Wolfram Language 95 94 82 bytes
Interpreter["SemanticExpression"][#~StringReplace~{"me "->"mes ","plus m"->"m"}]&

# represents the input for the pure function.
If necessary,StringReplace replaces "time " with times ", "plus minus" with "minus" (through "me "->"mes ","plus m"->"m", respectively). The shortened replacement forms, suggested by lirtosiast, saved 12 bytes.
Interpreter["SemanticExpression"] does all the rest.

Can you change "time "->"times " to "me"->"mes" and "plus minus"->"minus" to "plus m"->"m"?

Yes.  Excellent suggestions.

05AB1E, 166 147 141 139 135 bytes
„byK“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“#vyN:}'tK'…§¦'+T«:'°¡„ *т«©:.•1×j›o!ĆÖ•3ôŽ9oS:'y®¨:©“‰´Øè„Æ€ººß“'tK#UX¡εð¡õK2ôJ.EO}®áX"+-**/"S:Sðì.ιJ.E

Way too long.. Will try to golf it down from here.
-4 bytes thanks to @Emigna.
-2 bytes thanks to @JoKing.
Try it online or verify all test cases.
Explanation:
„byK                 # Remove "by" from the (implicit) input-string
“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“
                     # Push string "zero one two three four five six seven eight nine ten eleven twelve"
 #                   # Split by spaces
  v   }              # Loop over each of these items:
   yN:               #  Replace the item with its 0-indexed index
'tK                 '# Remove all "t"
'…§¦                '# Push string "teen", and remove the first character: "een"
    '+              '# Push string "+"
      T«             # Append 10: "+10"
        :            # Replace all "een" with "+10"
'°¡                 '# Push string "hundred"
   „ *               # Push string " *"
      т«             # Append 100: " *100"
        ©            # Store it in the register (without popping)
         :           # Replace all "hundred" with " *100"
.•4º»Ÿć'Rþн•        '# Push string "wenhirforfif"
            3ô       # Split the string into parts of size 3: ["wen","hir","for","fif"]
              Ž9o    # Push integer 2345
                 S   # Split to digits: [2,3,4,5]
                  :  # Replace each
'y                  '# Push string "y"
  ®                  # Push the " *100" from the register
   ¨                 # Remove the last character: " *10"
    :                # Replace all "y" with " *10"
©                    # Save the current string in the register (without popping)
 “‰´Øè„Æ€ººß“        # Push string "plus minus times time divided"
             'tK    '# Remove all "t": "plus minus imes ime divided"
                #    # Split by spaces: ["plus","minus","imes","ime","divided"]
                 U   # Pop and save it in variable `X`
                  X  # And push variable `X` back again
                   ¡ # Split the string by those operator-strings
ε          }         # Map each substring to:
 ð¡                  #  Split by spaces (NOTE: cannot be `#`; if the string contains no
                     #   spaces, `#` remains string, whereas `ð¡` wraps it in a list)
   õK                #  Remove empty strings from the list
     2ô              #  Split the list into parts of two
       J             #  Join each pair together
        .E           #  Evaluate each as a Python `eval` expression
          O          #  Sum them
®                    # Put the string from the register to the stack again
 á                   # Remove everything except for letters
  X                  # Push variable `X`: ["plus","minus","imes","ime","divided"]
   "+-**/"           # Push string "+-**/"
          S          # Split to characters: ["+","-","*","*","/"]
           :         # Replace each
S                    # Split the string of operators to loose characters
 ðì                  # Prepend a space before each
   .ι                # Interweave all sums with these operator-characters
     J               # Join everything together to a single string
.E                   # Evaluate each as a Python `eval` expression (and output implicitly)

See this 05AB1E tip of mine (sections How to use the dictionary?, How to compress strings not part of the dictionary?, and How to compress large integers?) to understand how “¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“, '…§, '°¡, .•4º»Ÿć'Rþн•, Ž9o, and “‰´Øè„Æ€ººß“ work.
Step by step example:

Input: two hundred twenty two divided by two times minus fifty seven plus three hundred eighteen minus minus ten
Step 1: Remove "by": two hundred twenty two divided  two times minus fifty seven plus three hundred eighteen minus minus ten
Step 2: Convert "zero" through "twelve" with the correct number: 2 hundred twenty 2 divided  2 times minus fifty 7 plus 3 hundred 8een minus minus 10
Step 3: Remove all "t": 2 hundred weny 2 divided  2 imes minus fify 7 plus 3 hundred 8een minus minus 10
Step 4: Replace all "een" with "+10": 2 hundred weny 2 divided  2 imes minus fify 7 plus 3 hundred 8+10 minus minus 10
Step 5: Replace all "hundred" with " *100": 2  *100 weny 2 divided  2 imes minus fify 7 plus 3  *100 8+10 minus minus 10
Step 6: Replace all ["wen","hir","for","fif"] with the correct digit: 2  *100 2y 2 divided  2 imes minus 5y 7 plus 3  *100 8+10 minus minus 10
Step 7: Replace all "y" with " *10": 2  *100 2 *10 2 divided  2 imes minus 5 *10 7 plus 3  *100 8+10 minus minus 10
Step 8: Split by ["plus","minus","ime","imes","divided"]: ["2  *100 2 *10 2 ","  2 "," "," 5 *10 7 "," 3  *100 8+10 "," "," 10"]
Step 9: Split each on spaces: [["2","","*100","2","*10","2",""],["","","2",""],["",""],["","5","*10","7",""],["","3","","*100","8+10",""],["",""],["","10"]]
Step 10: Remove empty items: [["2","*100","2","*10","2"],["2"],[],["5","*10","7"],["3","*100","8+10"],[],["10"]]
Step 11: Split into parts of size 2 and join: [["2*100","2*10","2"],["2"],"",["5*10","7"],["3*100","8+10"],"",["10"]]
Step 12: Python eval each: [[200,20,2],[2],"",[50,7],[300,18],"",[10]]
Step 13: Sum each: [222,2,"",57,318,"",10]
Step 14: Re-push the string from the register, and remove everything except letters: dividedimesminusplusminusminus
Step 15: Replace "plus","minus","imes","ime","divided" with the operator characters, and prepend them with a space: [" /"," *"," -"," +"," -"," -"]
Step 16: Interweave and join both together: 222 /2 * -57 +318 - -10
Output: Python eval the string, and output implicitly: -5999.0

Haven't tried to make a solution from scratch or studied yours in detail, but I noticed one golf.

sfk, 572 449 423 bytes
This could all be one line, but for the purposes of reading it I used newlines instead of spaces.
xed -i
_plus_+_
_minus_-_
_times[ortext]time_*_
_divided?by_/_
+xed
"_[white][2 chars of a-z][chars of a-z]ty_[parts 1,2]0_"
"_[white][2 chars of a-z][chars of a-z]een_[part1]1[part2]_"
_ten_10_
_lev_11_
_twe_12_
+xed
_ze_0_
_on_1_
_tw_2_
_th_3_
_fo_4_
_fi_5_
_si_6_
_se_7_
_ei_8_
_ni_9_
+xed
_0[white][keep][digit]__
"_[chars of e-z ]__"
+xed
"_?dd[keep][2 digits]_[part1]_"
_?dd[keep][digit]_[part1]0_
_dd_00_
+calc #text

Try it online!