text:
Given a string and integer n, split the string at n characters, and print as follows:
Given a string and integer n, split the string at n character, and print as follows:
Ex)
laptop 3 should print lap top
laptop 2 should print la pt op (see how it splits the string at every 2nd char)
Special cases:
laptop 0 should print laptop (since we split at every 0th char, thus none)
laptop 9 should print laptop (since length of laptop < 9, so no splitting)
bob 2 should print bo b (we split at the o (2nd char), but then there aren't enough characters after, so we just leave as is`
You may assume n >= 0

What does "print it together" mean? Print with spaces in between, or just print it in any clear format?

@ETHproductions in the format I have specified, sorry for the confusing

May we print more spaces after the string output?

@dzaima no. thats why I made it so that if you do not enough characters after splitting, you just print the rest of the string (no extra spaces after the rest of the string has been printed)

Not a duplicate: This one is only part of the other challenge - and it allows builtins.

Can I print linebreaks instead of spaces?

Japt, 7 bytes
òVªLl)¸

Test it online!
Explanation
            Implicit: U, V = inputs
UòV   )     Split U into slices of length V.
   ªLl      If V is 0, instead use 100! (roughly 9.3326e+157).
       ¸    Join with spaces.
            Implicit: output result of last expression

9.3326e+157 is far larger than JavaScript's max string size of 9.0072e+15, so this will work for any input.

JavaScript, 54 47 bytes
s=>n=>n?eval(`s.match(/.{1,${n}}/g)`).join` `:s

f=
s=>n=>n?eval(`s.match(/.{1,${n}}/g)`).join` `:s

console.log(
    f('laptop')(0),
    f('laptop')(1),
    f('laptop')(2),
    f('laptop')(3),
    f('laptop')(4)
)

PHP, 48 bytes
[,$s,$n]=$argv;echo$n?chunk_split($s,$n," "):$s;

Run with -r.

Jelly,  7  5 bytes
sW⁹?K

A full program printing the result (or a dyadic link returning a list of characters).
Try it online!
How?
sW⁹?K - Main link: list of characters, a; number, n
   ?  - if:
  ⁹   -       chain's right argument = n (0 is not truthy, positive integers are)
s     - then: split a into chunks of length n (overflow kept like the challenge requires)
 W    - else: wrap a in a list
    K - join with spaces (the wrapped list becomes depth 1 again with no spaces)
      - implicit print

When I first learned Jelly, I didn't understand how ? could really be useful, but that's twice now in 24 hours... Dennis really can do no wrong ;)

So each conditional clause can only have one atom?

@totallyhuman they could be: single atoms; together a multi-chain-link (individually just called "chains"); referenced-links; or compound-links.

CJam, 11 bytes
q~:X{X/S*}&

Try it online!
How it works
q~           e# Read all input and evaluate. Pushes the string and the number n
  :X         e# Store n in variable X
    {    }&  e# If top of the stack (number n) is nonzero, run this block
     X       e# Push N again
      /      e# Split into pieces that long. Last piece may be shorter
       S     e# Push space
        *    e# Join using spaces
             e# Implicitly display

wow i dont think it can get shorter then this

@ETHproductions Aww. Thanks!

@ETHproductions Corrected

Haskell, 33 bytes
import Data.List
s!n=chunksOf n s

If not explicitly specified, the order of inputs can be arbitrary, so just chunksOf is a valid submission. In case the list has to be the first argument flip chunksOf is a shorter way.

Python 2, 76 67 56 bytes
-13 bytes thanks to ETHproductions and notjagan.
lambda s,n:n and[s[i:i+n]for i in range(0,len(s),n)]or s

Try it online!
Regex solution, 56 bytes
lambda s,n:re.findall('.{1,%i}'%n or len(s),s)
import re

Try it online!

Could you remove the and n?

@ETHproductions Yes, I can! Don't know what I was thinking. o0

I think you can do s,n=input();print n and[s[i:i+n]for i in range(0,len(s),n)]or s for 63 (note: I have not tested this)

@ETHproductions I was just about to suggest the same for 56 bytes.

Oh, you guys ninja'd me. >< Thanks!

Mathematica, 114 bytes
d=StringRiffle;If[#2>(s=StringLength@#)||#2==0,#,k=d@StringPartition[#,#2];If[#2<=s/2,k,d[{k,StringDrop[#,#2]}]]]&

QBIC, 27 bytes
_L;|~:|\b=a][1,a,b|?_sA,c,b

Explanation
_L;|        set a as the length of A$ (input from cmd line)
~:|         IF b (input num from cmd line) is anything but 0 THEN (empty)
\b=a        ELSE (b==0) set b to the full length of A$
]           END IF
[1,a,b|     FOR c = 1; c <= LEN(A$); c = c + b
?_sA,c,b    PRINT a substring of A$, starting at c, running for b chars.
            NEXT is auto-added at EOF


text:
Make a string into a triangle
Challenge
Given a string, make it into a triangle as shown below:
Input
Hello, world!

Output
H
He
Hel
Hell
Hello
Hello,
Hello,
Hello, w
Hello, wo
Hello, wor
Hello, worl
Hello, world
Hello, world!

The first line contains the first character of the string. The following lines contain one more character on each line, until the full length of the original string is reached.
If you receive a one character string, just output it.
You will never receive an empty string.
Rules

Standard loopholes apply, as usual
This is code-golf, shortest solution wins.

Have we really not had this challenge before?

@xnor Not from my searching

Second half of this

@WheatWizard Oooops

Trailing newline OK? (Is there a default?)

@xnor Sure I guess

Jelly, 3 bytes
;\Y

Try it online!

and of course Dennis crushes the competition within 3 minutes. GG

@Mendeleev By the way, even APL gets three bytes, ↑,\\

brainfuck, 23 bytes
,[[<]>[.>]++++++++++.,]

Try it online!

Python, 33 bytes
f=lambda s:s and f(s[:-1])+s+'\n'

Try it online!

J, 2 bytes
[\

Tailor made for J.  This is just a scan \ using the identity function [.
Try it online! -- Note the extra space in the output on line 1 is just a quirk of TIO in this case.  It does not appear when run in jconsole.

Better formatting: https://tio.run/##y/r/P03B1kohOuZ/anJGvkKagrpHak5Ovo5CeX5RToqiOldqRWbJfwA [\ would count as a tacit verb here.

Thanks @Dennis.  What did you mean by "count it as a tacit verb"?  Is 2 bytes not a fair count according to community rules here?  I'm still fairly new to this....

Yes, 2 bytes is fine. We allow anonymous functions, and that's just what [\ is.

Haskell, 28 bytes
g[]=[]
g a=(g.init)a++'\n':a

Try it online!
Pretty straight forward.  The base case is the empty string and each other case is a recursive call to init to the string with a newline and the input added to the end.
Here are my three attempts at a non-recursive solution all of which are exactly the same length.
g a=concat['\n':take x a|(x,_)<-zip[1..]a]
g a=concat['\n':take(fst x)a|x<-zip[1..]a]
g a=concat['\n':take x a|x<-[1..length a]]

And here's one that I found that is shorter than all of them
g a=do(x,_)<-zip[1..]a;'\n':take x a

I also came up with this very strange solution I quite like (its longer than the others though):
g a=zip[1..](a>>[a])>>=('\n':).uncurry take

Try it online!

V, 5 bytes
òÄ$xh

Try it online!

Python 2, 49 bytes
lambda s:'\n'.join(s[:i]for i in range(len(s)+1))

Try it online!
Meanwhile, I'm like, how is this is impossible right now in my language?!

Python 2, 34 bytes
s=''
for c in input():s+=c;print s

Try it online!

C (gcc), 57 bytes
i;f(char*s){for(i=0;i<strlen(s);puts(""))write(1,s,++i);}

Try it online!

Ruby, 31 + 1 = 32 bytes
Uses -n flag.
a=''
$_.each_char{|i|puts a<<i}

Try it online!

Why use a newline instead of a semicolon? Newlines are bytes too...

Newlines are more readable.

Ruby, 35 bytes
->s{a='';s.each_char{|c|puts a<<c}}

Full program seems to be shorter.

@Phoenix I noticed.

source: Stack Exchange

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

sort: votes


text:
Lorem Ipsum Generator
Lorem Ipsum is placeholder text used when preparing layout without wanted to have content already filled.
One of its key features over using some arbitrary text is that it is nonsense.
It isn't even valid latin (though it is close).
This prevents anyone being shown the layout from becoming distracted reading the text.
The other key feature is that it looks like real language.
The words are the right length, and the characters occur with the right distributions.
A problem is that the Lorem Ipsum is not necessarily good gobbldy-gook for all languages, or even for all subject matter.
We expect that the distribution of letters would be different in a novel, than in a scientific article.
Your task thus is to create a tool that when given an example of text, generate a lorum ipsum style gobbldy-gook that is a suitable imitation of the characteristics of that text.
The Task
Given an input in UTF8 text input-text, and a number x.
Output x characters of gobbldy-gook following the style of that text.
It may be assumed that words are separated using the space character in the input text.
You may take the input in any reasonable form (though it must be able to accept UTF-8). Eg reading from STDIN, reading from file, as a string passed to the function etc.
Similar for output.
Critria

Must not be real correct text in the language of input-text

In particular must contain no words with more than 3 characters from input-text.
This can be trivially avoided by using a hashset to ban all words from input-text from occurring in the output

Must look like it could have been real text from the language of input-text.

That is to say it must have the correct letter and word length distributions that is convincing to the eye of the reader.

It is up to the implementation if they take this to mean unigram, bigram, trigram or other statistics for the distributions.
The goal is for it to look right

Judging Texts
For purposes of judging please provide 256 characters of output based on each of the following public domain texts:

De Finibus, Book 1, sections 32–3, by Cicero.txt
Pride and Prejudice, By Jane Austen
Die Verwandlung, by Franz Kafka
The Magna Carta

gist with all files
Those that these are all UTF-8 encoded, and in particular Die Verwandlung, being in German uses many characters outside [a-zA-Z]

What's the winning/scoring criterion for this challenge?

@LegionMammal978 It is tagged popularity-contest, which means the judges will be the voters.

This reminds me of the time I wrote a Markov Chain program to generate several pages of grammatically correct English gibberish (real words, real grammar) to submit to a "write fiction badly" contest. It (and the entry I submitted the following year) were sufficient to get me banned forever (and subsequently forced to judge).

Python 3
import string
import random

with open('lorem.txt') as f:
    text = f.read()
number = eval(input("Input number: "))

dictionary = ''.join(ch for ch in text if ch not in set(string.punctuation)).split(" ")

chars = []

for word in dictionary:
    for char in word:
        chars.append(char)

chars = list(set(chars))

occurences = {}

for char in chars:
    occurences[char] = []

for word in dictionary:
   for idx, char in enumerate(word):
        try:
            occurences[char].append(word[idx+1])
        except IndexError:
            pass

lengths = [len(x) for x in dictionary]

result = ""

for _ in range(number):
    length = random.choice(lengths)
    word = random.choice(chars)
    for _ in range(length):
        try:
            word += random.choice(occurences[word[-1]])
        except IndexError:
            break
    result += word + " "

print(result)

Takes text input through a file named lorem.txt and number of words through STDIN.
Samples:
De Finibus:

bolute moresu xisi libospssev lolu ute tamqump Sercolimo mnci iaerue unt xptemp ptur xiui mumnsc ner citerum hiositius fun Set llu hibol etet mpesi amitap voserata mol iumol ospe pte ell asequmut

Die Verwandlung:

Frehwauchmi «
      vo ineic venzundenwasender geitende «
      darenenserttem Semint estt Scklode
      Zur
      g ZenÂ»e Orer urd cher
      s
      Bet
      kun renaunn

Pride and Prejudice:

paime k
      hothenoc 5
      “ 230
      erth ZZWedomincab Mrevoueim Vifedrctogei Come Kidi yol qul
      “Thant Kie Rag 41
      mf vate 12
      Eled 8
      Dathed 1
      mb Bed
      “Y merie xto zasorl h’sh ghasst Wha quce skeniat zan dishond
       othing
      hare hing din

And finally, the Magna Carta:

wincand zisend
      s
       Pes CEFured indons fequ dindshay ranen Gofun
       OURore ibec 6248 Rofonestheasaven
      sul nthal
      232 rend
      matyont r
       uiconlicend
       ucriof 7 ashesevenye Gerd
       BEndrouse IIns jurig 20000 UREndit mandira 0000000000s
      a
      wic 47 Enccet

It's not my best work.
All I'm doing here is some simple Markov chain recreation of the original text, with word lengths taken from a list of all lengths in the given text.
I sort of hoped for better results, but oh well.

Looks like you are having Unicode issues with Die Verwandlung.
As ¼ never occurs in the original

Sorry, I saved the file in the wrong format. Should be good now.

'ch for ch in text if ch not in set'

Clojure
This was hard! I started this last night at 9pm thinking I could knock something quick out, no problem. All the little problems I didn't realize when I started began to pile up though, so I had to put it on hold until this morning.
It's still not great, but it does the job.
Note: For some reason, IntelliJ/Cursive's REPL (which I used to test and generate the phrases) can't accept code greater than 65k chars in length, which means I couldn't simply paste some of the sample texts into the REPL. I tried reading them from file, and for some reason accented characters aren't being read properly, despite specifying UTF-8 encoding. As a workaround, I used subsets of the texts to act as the sample to generate from.

De Finibus:

vitsmai qomsme tainrte,e qanerim toaurtatt roliaum veaiieq foimpq smarsu mneurutds drtameitt vndnceui cesolleqd Ambrsuou hntumetni euuhcqitu eoseiuane fusipdm,t depamme vofuuet uamsel aumsatet aaee.idu, metosa etqirtai ialisua vsleataa vellpuen aalui, celaqa eultnsec celili eolisi,t qcrm,qets qolniani earure elfucnsn donate qitua,at. aimaau dmgaim aeumltn qori,et cogerentt serlitmt. uaqua,dr aososlt dulir,m oelmmc ietiqctti aupniuon semionu aerciamti qlmomi hinldt htnuaiqa cnnoot cetultad nutcliaa aolstu puouru nfiuitmiu lapopttr rxsutea ood,rut aiseuc quoe.rmi ntiemhb ueter,sb delsrias titopduto qurorcd,t vxiupsi sem,reer iaeesit, mooila eolnoa infosmese exni,uns qtnpeet peiealna lolopt duosrtun oufmttn omsarhdsa veri,rme doilrnt hulstqo cxlusa uasputua qtlpl, certppmtd qopu,tmi oonires oosoia fu,iepa eedumtn,e sesiot,t rtioeam helnora rrnoeeas aslceiist ealimtdd qolsmnas eetgoeta tomema eemurst exoacumtn tuioeq,sa vtauctdst oarittsbt lonpstoa, famade,qa empoenuti minisatie vuiuseuis bxnmii nafuiemsi plscrt vusuiiu macirs cugaesa vttsitm dumudta ruluiqu easimin vsceicnt tuqmeiuns aoitm, inaulnac vfsioe,nu iomistaa. qalisi lanurr eiutma qesbtdi eprurni qintp,iim iuiamt setuoteee qugpeau hfge,e eosqpe dicemte vamerdm noluisi euceaaa eliiutii iinnat ioiuraa aubie,uat ctret,u ruaemi,a, noq,re dupiet eugesr nsnosema ouseipon qasupeeci axtilemt aaaedmdni tssimac ouptpicii notunein qiclo,ist eetummea aelste aictd, vanerean qulurus fenumit, ciieriste dtascec eolirliee bemuam qactiiaei cirudadn qupespase eerqednb vaiimua ltmemsia mucnpu qpmttea militu outpeqct caiomeetu mid,semd ailudtm eumcpri duniics negusqat nunnsu nobod,ntu aoss,it mopaueta dubupntao Seluoiatd atteresc ouisrmn mutdri ee,iri lonoeuo meirqudi montutut qre,ain foitute vaiupmi seilpusin eaoeei,i eetldidse heguise fetbra,sd deri,ssai qirrpcua dothii qiioutub dol,iem moacdss uocr,iit eassrreti ilouptutd qtgupc qiuicet vtiusitam aesupti qaileats qobeee, qornstesi tucpmitna sunuoqdt noclunmc eopisstr aicnppts suuimtett telom, ontimtc aosoren,i stbirstre qpctd,tb aunviu eapaott dnrutmt eoiure iiliei sulootitd iepidtsb, excpraii factm,tse outittt fbgira suaapeiut atniiet vuiireo vtes,eisi qtseueai qour,ea

Pride and Predjudice:

eoonr. Wosr sotd. siwlt aaaer” ohe” osxalp shrprc afel nhsn ttydt aetr ohtti aotu.n tonl bouno Inui woptur weomtf hhnars ohte oisms Laurl _nje_y thr_ Mofl,d aist! rdne snage iasi mier.n onen bolh myyier Nont,c hian ihl!i Bcs””r aoei jewesr Msuwh wodeed aiuwdd arssl” efae mosnlb fuqet onsm “e,eeo vereen roor tlrli” nm.p tsrtid auitl aigm yhru shurr sontav yene. esug hoyvot “odhg ahenke coufn hhcer mike:l mfol heae oadiai iooi fotzdf piey ofu? shn,tc Iied Ihnrg mhoihs naurn IIahkk mosi nfolc Mfekei gieu deoei iHnu ivtu huuti Bo.tsi rysnei mirvn ered are,e ooel wIae Temmoe qoyu fetee, ynhd nontui hgnw aaye fet.kd irro “gtp noatk inrn isdstt tDun thde ohulie watw teness veeee, Mhntsr sai.s Lodue Iteref niergr thst luegn tsuned wii,e, taes iemtsh lhuhs ys..s hahie eehren unet haettd fam.i thurl Lptm our hftle ar.nna ayeoeg hem.,r whnn oner foiet- Bhfe “o.mll thue yoyh cory aean Mehg ho,ncs falntn nstu tnse,. dnutni weuee olmpt ay.nnu coeso lyeteg ancy,p iffg ihele Ooreen arrn “akyan tttn cxno nomi “heh momee an.ra tosts, Efee afi! arow ynele io.z teocr aids sore ioog shrr hmrve aynri Braus guaein bouree lupa aB,.t inru hnuu todnl thdiyi hvanwa botvu hidiet Nilie toa.y wothn. nesth Ioia mhoob whdr tYen oosl yehg Molt mokdn gonetf shrle toieg tooet He,lh bu.ead datog “aru atre soym eiomar yose mome htas, Lonr “otets oidrsi hwanes yimr! anelsh Bhst tNn; fhang, talp mirn “oklbt “eod” dorhit hopc ieddn Maae Bnelp tuuovg iWne co,ye ghsee fa!rn MTenee vodnr hu.a aatrel hoehs yfnmc Meog oenec prrn ieuwae “olei

Die Verwandlung:

inrter Bninrl aäshsi zictth ztgtee.n ireztnr ereoo«de dlifc su,rienn dicgi! duechre gädkean iafiu hbrhür,e öamk, auehse, fhgltr ernsme urcttm uGmartrt eacge wungu eeelle üaise,n dantrid s-ßenn Tamrsd, ierosne fifn, satfg decnt Firüncr goztfekh urcfenl zrg,t donet fartan eishgta eo,dt mrnagks Cutterc iirlo uufbea Wsnhdh hages iicrelnn wimbs wickon Pehuelö? uuertn eleezn üewnlnäe zeiüriti Pidhi Feldaet Banec ahleßelk Nanpüehn eedeuh elflt aüagn mogteäg wehhhorr for,tt h-trtlg öoßdrit Teaue aaedeee necmär vingrrha hai,h vidos ncsne,ne nurlurns Uomeer vrrecoü kcphtd uhrleßl neeke dcrhth amämtza dehbsn Meftet,e dnlwenei Gigrser zagnüe srrcse Wenstt asnbhn Zägele Eebeefn eerhte dihee Nernta. saheter Uihöu fitfu aibeeens Einre Banwf vaneine eardtg fnebtn Sihne hontn hemte, uecßred arrdhe dollnän. Juhno gasdee eeelhn wonlht Aänsüenr vlrssf Dowtlhin Ueeseasl iusnu namhie Binziae wieleet bucdrne maselort Süfiwr strzgdlg dGnite sifgh iusecti Dohutl eucl.g Bbrstnih amehn,üc sarlhe vcredrne krlnat dbrnra enimsnhs larwrn docdää karho Zaths »ersnnhf weire Tirhee drrhm?s iesetehu ialneke geihc disege larsuet, mrintm Ginhdrhe eoieu Msitpn rarzeut, eahßl düernäde eugchn enean zenüor dertnhe Inheuer dlctßcim fitimok hrrsnec säscl Seletete grßrtdce Kunenh bameänßn Wirmg heluhst Uensi gärnre döarrct wrnw,wel datbc Raree lonse mcrseuf aetoet rrncär wrcgelm saste Zirpe uewl,t wceeeskr Aismttme ketfer hnssen Pind,e, einsr?e! diflec mlrlcnft »umgeiß sär,ed nodfst Hbdßen Weensel finhedd lunnt dehsnrg fibsin.a hictfet« vrgturs lehntnm leektfrf brehrrnd brlen eorfem srsgenrn Ditreeen girzee iigeenie devr, daelmrs eanlecse iootohca durgt dalmce srzsh dihrugnt Bbtrwsg iDre,nil aeegesüt Irfcdr etcnruec mlaznegc setirkh Sehteeec kinlaret Ubetetlc gnßfeot eieiuen kantgr wackt -usltrm kereä eerben sahendfh nusarnd ialaac decfear hofüei wbmtee! srnper eegik nünnh woiieb« derlee« dregeeee danhele deetpi gmraeeg esaaez z-täe

Magna Carta:

giotei ooeleeg majegcg aorses fernpt sekml mhmt,p tfaGta deoel (n8rsse andpi ufaih fnoseu efaes hhod,i wieer hogd,e boeer soin IwsoRei bed)t fogds tipdfr neylnme ouehps oedhhem Chuaee hst)sr oascs werooen ou'hin hhansn ofecdsd towsof alee, lube'a Gosisfr boceeae ahdbee laaeh tngdc hheoTct (oyce ouedoe' dnysscg beenru hocOo Jshlsee kralse juilihaerhs walreno (nlln troll onoplat dw9ed senroc aolpmdt toedhh gerdc eiype beilsr gbeibet pedns le.rsu aamtnon aoenri tsiaey torrtv oamle snvsn faaorw dhrss arrber Thvsat rafgmu thnslp pnnril rfrsrt letol whhle Ifoehog fhaeos. trthon fukmrnn hnkei otrvt bieyl armbs mneh, felycmg weter mfhte direon' Ma0slo leelo ane'r hneh, Fress snurwe seaoas poevoc, dasee heeeic, efn)lss gtct- eo9laip wnrrlit lyyei, gndosti oecoe suroe taftu bieel feolrg oortefd loatfv -rleln tacblst Nnrcr nOnnr rtimhc toahlfe Wirrn brfbo aecrhb whehri ohnmi walnn oeorlfs rhpsene cauppn woitsns toynr heapihd oanetd ofghen Nfesrtf gamerg desolsf gr.roeb i9drnf uodthn tnrehne wuae'l iutsse Eonllse poplrsa Ghoel m4teest ffest tauec i3pall, shent, gwadi sitcra ifsoo, Wivwn s1tdeur bagersa fead.,g teseus rncdrne hangss thzel aents ienus, binseae (osa.re trrrs of)io eyfgo, trrml oiado sumsn weygrch ahmlvnn tuednt utepsit iota- Ehe.lm crtlot aet)r crblras aenelf, tupmtae Eelee wtoerrd rfant ifldd fhyalt ffdog thuho tists, teadhl nadtoat tflda, Aielsd otreli trrn,mc feeneut nndcdeu hhnlv lidea, titges afrit wrkor eev)lt, fndni hrmml)d tegvee Ihr,nnf kvqoe cnentr Nedtl onmebba hhwdee eopoi aonthnl aautle uflhu. Retan shclaer Jostsi *prdz ebnnlc ferde hiepraa oa9)eat lisvyn nilos brslbwe btyson aoncs,vi,t tntter stret cifgile tuslene kivtle irmie aylrie Faala-e aneies gatoy wuomsne shyah snoio.d afeh'a drfree khvoget wicrsns caves, hheto (blfs sheoue

(ns mandelbrot.loremipsum
  (:require [clojure.string :as s]))

(defn rand-word
  "Generates a random word based on what letters appeared at what index.
  If the index doesn't exist, it pulls a random character from the sample-text."
  [length pos-map sample-text]
  (apply str
    (for [i (range length)]
      (rand-nth (get pos-map i sample-text)))))

(defn safe-rand-word
  "Helper that loops while the produced input is in the exclusion set.
  May get stuck if the sample size is too small."
  [length pos-map sample-text exclusion-set]
  (loop []
    (let [word (rand-word length pos-map sample-text)]
      (if (exclusion-set word)
        (recur)
        word))))

(defn rand-word-len
  "Generates a length based on avg-len +/- an amount in
  the (range (- deviation) deviation))."
  [avg-len deviation]
  (+ avg-len
     (rand-nth (range (- deviation) deviation))))

(defn pos-letters
  "Records what characters occured at each index of each word."
  [words]
  ; A two dimensional reduction.
  ; The inner reduction takes an existing pos-map, and updates it with information about the word
  ; The outer reduction combines all the word pos-maps together.
  (reduce (fn [pos-map word]
            (reduce (fn [acc [i chr]]
                      (update acc i #(if % (conj % chr)
                                           [chr])))
                    pos-map

                    ; Maps with the index of each letter
                    (map vector (range) word)))
          {}
          words))

(defn gobbly [n-chars sample-text]
  (let [; Split the text into words, then place the words into a set
        ;  to ensure that they aren't generated.
        words (s/split sample-text #"\s")
        word-set (into #{} words)

        stripped-text (s/replace sample-text #"[,.?!]" "")

        ; Figure out the average word length, then calculate how much
        ;  deviation should be allowed.
        avg-word-len (/ (count sample-text) (count words))
        length-deviation (/ avg-word-len 4)

        ; Find which characters appear at which positions
        pos-map (pos-letters words)]

    ; Generate n-chars many characters by...
    (doseq [n (range n-chars)]
      ; ...printing a space, then a randomly generated word.
      (print ""
        (safe-rand-word (rand-word-len avg-word-len length-deviation)
                        pos-map
                        stripped-text
                        word-set)))

    (flush)))

Use it like:
(gobbly 256 "KNOW THAT BEFORE GOD, for the health of our soul and those of our\nancestors and heirs, to the honour of God, the exaltation of the holy\nChurch, and the better ordering of our kingdom, at the advice of our\nreverend fathers Stephen, archbishop of Canterbury, primate of all\nEngland,")

So it is based of P(letter | index in word), rather than n-grams (as used in a markov chain).

@LyndonWhite No clue. I have 0 experience with NLP lol (or whatever study that is). This was just the first method to come to mind. Yes, it takes into consideration what place each letter occurs in each word, and tries to replicate it. Its quite flawed though, as letters that are supposed to occur at the end of small words appear in the middle of large ones, but it's the best I could do. I suppose I could have had different pos_maps for each word length, but I didn't think of that at the time.

Can someone comment on the downvote please? I'm the only one who's downvoted at the same time the challenge is closed?

Python 3
I chose not to assume almost anything about the source language. In particular, I chose not to give any special meaning to anything except for whitespace. Therefore the code doesn't generate sentence-like constructs or valid quotations, but doesn't get worse with another language with different "syntax".
The heart of my code is a Markov chain. The first part of generate() parses each word of the text, collecting the probabilities that a certain character appears after another one in the text, along with some extra data.
The second part of the code then generates words based on those probabilities, along with some validation and modification:

The Markov chain only generates characters that appear after the previous generated character in the source text.
The lengths of the words are distributed as in the input. If the Markov chain does not know how to continue generating a word, it is discarded.
A character must have existed in the current position in a word, both from the start and end. (For example, for input "a-bcd," e. a dash may only exist as the third character of a word.) This removes lots of wonky punctuation. After 1000 tries the code may allow an invalid character.
Each character is made uppercase with the same probability that the character in that position is uppercase in the source.
"Real" words are discarded by a simple set lookup.
The whitespace between words is picked from the whitespace sequences in the source.

Code
def generate(text):
    import random
    def increment(dic, key, mid = None):
        if mid is not None:
            if mid not in dic:
                dic[mid] = {}
            dic = dic[mid]
        if key not in dic:
            dic[key] = 0
        dic[key] += 1
    def pick(dic):
        total = sum(dic.values())
        pos = random.randrange(total)
        for key in dic:
            if pos < dic[key]:
                return key
            pos -= dic[key]
    words = text.split()
    markov = {}
    allchrs = {}
    lens = {}
    white = {}
    poss = {}
    uppos = {}
    valpos = {}
    pos = 0
    prev = 0
    for word in words:
        increment(lens, len(word))
        if prev:
            pos += len(prev)
            whi = text[pos:text.index(word, pos)]
            pos += len(whi)
            increment(white, whi)
        prev = word
        curr = 0
        for p, char in enumerate(word):
            increment(allchrs, char.lower())
            increment(markov, char.lower(), curr)
            increment(poss, p)
            increment(valpos, p, char.lower())
            increment(valpos, p - len(word), char.lower())
            if char.isupper():
                increment(uppos, p)
            curr = char.lower()
    words = set(words)
    output = ""
    while True:
        append = pick(white) if output else ""
        wordlen = pick(lens)
        while True:
            prev = 0
            word = ""
            valid = True
            for i in range(wordlen):
                if prev not in markov:
                    valid = False
                    break
                for _ in range(1000):
                    char = pick(markov[prev])
                    if valpos[char].get(i) and valpos[char].get(i - wordlen):
                        break
                upp = random.random() < uppos.get(i, 0) / poss[i]
                word += char.upper() if upp else char
                prev = char
            if valid and word not in words:
                break
        append += word
        if len(output + append) > 256:
            break
        output += append
    return output

import os, sys
for file in os.listdir():
    if file.endswith(".txt"):
        print(file)
        with open(file, encoding="utf-8") as stream:
            print(generate(stream.read()) + "\n\n---\n")

Output examples
De Finibus
This one is probably the best for my code. Almost resembles lorem ipsum.

do volllem ptem funsc sumoloduma arec aderodi iupen vonsteretae et, pt atisatus monce qupll remeris sasps am coria cecumaedaii ro an isii da vot esi Erenemonere lo vol lasuama min do oluaecodaer coluse ptrel bea ata, ctati vonditacetes mm oma oventquia

The Magna Carta
Looks a bit like Spanish.

bl oranr tr wighibintert han ma am mmpe "im noreervetord h
olandiale tll afin ssh iany hor 48) touro oelllll ce rc ome bl tse pale ota Edeid fonnny," disen oc nd,- kindi ccofore mamar mo hakne fr
beneth te byse me sur hindesweay
ane me rciven asho shidi

Pride and Prejudice
Again, English is hard.

hendver gh th,”
te ther y.” wherorath pprmyo it_t un? stro wam wllyserinof hish ac Wfey’sm sar.” wenenonto ther chu The, L ryo jounddle.” asis i
fto ok il warano rrithiel
amsti hes weteran ay.’sthinsti
merlisomos, asth “llle Hellye yerg
mer ady syo

Die Verwandlung
This one looks almost like German, but gets a lot of weird punctuation.

h
den. zunder an,« di grhtsck ieit erimie Len De ihttergommkor kkuc aledoht hrserogo ereschla Ateg seneichier-,« gonu imori hr sch demaßti aglfhl iht Rnde au Igeng,« ding üb ukrtl iemen dein Wehle nkt ieiei Ügenifregr En g mirgs sworer zwi blimmi er,« kb

The program's own source code
what(wils(le uenc rumid dent pp ren
    ifot inc inos(itpendi pr iss imit
                wor f uenete me orditp ds ourdinorkemit()
                    ist(whar wori nserev[preval "
                    sp iminderreralin):
            m

um
        inc

This does not really look like German... XD

@MegaMan Well, tried my best. I think some of the words resemble German ones.

Python 3
This code is very heavily based on the text generation example program from the Keras machine learning library. It uses a Long Short-Term Memory (LSTM) recurrent neural network trained on the data to generate the output character by character. I would've written the LSTM implementation myself, but I didn't want to reinvent the wheel when there was already such a good implementation that was capable of performing the task at hand.
The input is taken in a file named input.txt and is output to out.txt. I originally just used STDOUT, but Windows CMD didn't like trying to output utf-8.
The output could be improved on longer corpuses (i.e. Pride and Prejudice in the four that were given) by increasing the number of epochs the model trained for, but the runtime for a long corpus was already quite high, so I didn't bother doing so.
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers import LSTM
from keras.optimizers import RMSprop
import numpy as np
import random
import re

PATH = 'input.txt'
DIVERSITY = 1.0

text = open(PATH, encoding='utf8').read()
print('Corpus length:', len(text))

chars = sorted(list(set(text)))
print('Total chars:', len(chars))
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((i, c) for i, c in enumerate(chars))

regex = re.compile('[^a-zA-Z ]')
words = {word for word in regex.sub('', text).split() if len(word) > 3}
print('Total words:', len(words))

maxlen = 40
step = 3
sentences = []
next_chars = []
for i in range(0, len(text) - maxlen, step):
    sentences.append(text[i: i + maxlen])
    next_chars.append(text[i + maxlen])
print('NB sequences:', len(sentences))

epochs = max(1, min(20, 200000 // len(sentences)))

print('Vectorization...')
X = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool)
y = np.zeros((len(sentences), len(chars)), dtype=np.bool)
for i, sentence in enumerate(sentences):
    for t, char in enumerate(sentence):
        X[i, t, char_indices[char]] = 1
    y[i, char_indices[next_chars[i]]] = 1

print('Building model...')
model = Sequential()
model.add(LSTM(128, input_shape=(maxlen, len(chars))))
model.add(Dense(len(chars)))
model.add(Activation('softmax'))

optimizer = RMSprop(lr=0.01)
model.compile(loss='categorical_crossentropy', optimizer=optimizer)

def sample(preds, temperature=1.0):
    preds = np.asarray(preds).astype('float64')
    preds = np.log(preds) / temperature
    exp_preds = np.exp(preds)
    preds = exp_preds / np.sum(exp_preds)
    probas = np.random.multinomial(1, preds, 1)
    return np.argmax(probas)

model.fit(X, y,
          batch_size=128,
          epochs=epochs)

start_index = random.randint(0, len(text) - maxlen - 1)

generated = ''
sentence = text[start_index: start_index + maxlen]
generated += sentence

for i in range(1000):
    x = np.zeros((1, maxlen, len(chars)))
    for t, char in enumerate(sentence):
        x[0, t, char_indices[char]] = 1.

    preds = model.predict(x, verbose=0)[0]
    next_index = sample(preds, DIVERSITY)
    next_char = indices_char[next_index]

    generated += next_char
    sentence = sentence[1:] + next_char

generated = ' '.join(word for word in generated.split(' ') if regex.sub('', word.strip()) not in words)[:256]

file = open('out.txt', 'w', encoding='utf8')
file.write(generated)
file.close()

Examples
De Finibus

uos et ndllitilum lollreaces vetnocoptam llpe calateciae dorlstem veluatirem.lu ex ept is eptlet neteceppir idararer laror pt lolor.aesuptis caut doquia fiis solopet sen et at nxt at ex ditor aem oond, eo er di iolletiu pllnetaisec cec caperi mi, nd rorxme

Pride and Prejudice

Let us at a too
appear icovoim to seen
adeain and misougnor. Mr. Coilins
count; mander it had nearbaryt tordse sithing
naly mone agains at tullnearn of alfactained, illed the eavougant one; but her tamed a retoufly gilliction of her may nos. Comberuable.

Die Verwandlung

rer du nur ers unbeilnmit und wortst zu dinmaunn.« raue gewisch, schof sau damach.« rang, den sie ihrel erspiefen.
allech gegan kammer
mihr ihr, als die Gertüs»allen; den
BeHohden, umschof hatee und das höbem In
zu neune Stume, daß vornpiel gemößtigeß, am

Magna Carta

s by as by geards, and the improved of we renaiss-fur others
of any restice of by our welr the issuen the
ard or is Gid insumed to a sarilly ragalint, marners, sim in.
B2. And oney and rentershss lard bagean,
in te heish in af any out itfordedvers foroth

Cool idea, but I see real words in the generated Pride and Prejudice text.

@Carcigenicate Hmm, it seems my filter for the words isn't quite working; seen and appear managed to make their way into the output (the other words like tamed didn't actually occur in the corpus, and instead were found in other words like untamed). I'll take a look and try to see what the problem is.

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


text:
Product of Divisors
Challenge
Given a positive integer, return the product of its divisors, including itself.
This is sequence A007955 in the OEIS.
Test Cases

1: 1
2: 2
3: 3
4: 8
5: 5
6: 36
7: 7
8: 64
9: 27
10: 100
12: 1728
14: 196
24: 331776
25: 125
28: 21952
30: 810000

Scoring
This is code-golf, so the shortest answer in each language wins!

Interesting note (though probably not that useful for this challenge): the product of all divisors of n is always n^((number of divisors of n)/2).

05AB1E, 2 bytes
ÑP

Try it online!
Explanation
Ñ    # divisors
 P   # product

By first look I'd say this solution belongs under P, but something holds me off..

This problem is obviously NP.

Japt, 3 bytes
â ×

Try it online!
Explanation
â ×  // implicit integer input

â    // get integer divisors
  ×  // get product of array

Damn it, how did you ninja me?! :p Will delete mine when I get to a computer (whenever that might be).

@Shaggy I'm surprised, since I just found out about both â and × when writing this answer

I was slowed down by the min. character limit!

Python 3, 42 41 bytes
Saved 1 byte thanks to Leaky Nun!
f=lambda i,k=1:k>i or k**(i%k<1)*f(i,k+1)

Try it online!

(1,k)[i%k<1] is equivalent to k**(i%k<1)

Jelly, 3 bytes
ÆDP

Try it online!

MATL, 3 bytes
Z\p

Try it online!

Haskell, 35 34 bytes
-1 thanks to ovs
f n=product[x|x<-[2..n],n`mod`x<1]

Try it online!

Alice, 12 bytes
/o
\i@/Bdt&*

Try it online!
Explanation
This is just the regular framework for decimal I/O:
/o
\i@/...

Then the program is:
B    Get all divisors of the input.
dt   Get the stack depth minus 1.
&*   Multiply the top two stack elements that many times, folding multiplication
     over the stack.

Factor, 43 bytes
[ dup [1,b] [ dupd divisor? ] count 2 / ^ ]

Try it online!
Uses the formula n^((number of divisors of n)/2).
Usually mod 0 = (7 bytes) is shorter than divisor? (8 bytes), but the latter is used here to auto-load math.functions to disambiguate ^ (which happens to appear in a regex lib). Auto-use is weird. The unambiguous alternative to ^ exists (fpow), but it's longer.
[                ! anonymous lambda
  dup [1,b]      ! ( n {1..n} )
  [ ... ] count  ! count the elements that satisfy the predicate...
    dupd         !   ( n i -- n n i )
    divisor?     !   ( n ? ) tests if i is a divisor of n
  2 / ^          ! halve the divisor count and raise n to the power
]

Factor, 45 bytes
USE: math.primes.factors
[ divisors product ]

Try it online!
Uses divisors built-in, but obviously the library import is expensive.

Pyth, 6 bytes
*Fs{yP

Test suite.

Neim, 2 bytes

Try it online!

Me scrolling through answers: plain monospaced code, plain monospaced code, plain... bold, serif code? :-P

@ETHproductions Hehe.

@ETHproductions I actually coded this answer on iOS which means I can't actually see the characters.

That's... quite impressive.

@ETHproductions remember ESMin?

@MamaFunRoll Now that is a name I have not heard in a long, long time... ;-)

@ETHproductions Well, at least Neim has a codepage...and ESMin is essentially superseded by Japt...

@EriktheOutgolfer ESMin is/was a completely different beast from Japt... it had a codepage, but the codepage was had 1024 chars :P

@MamaFunRoll Well, they're both essentially JavaScript, just ESMin is much longer and uses Unicode. ;)

R, 28 bytes
v=scan():1;prod(v[!v[1]%%v])

Try it online!

x86-64 Machine Code, 26 bytes
31 C9 8D 71 01 89 F8 FF C1 99 F7 F9 85 D2 75 03 0F AF F1 39 F9 7C EE 89 F0 C3

The above code defines a function that takes a single parameter (the input value, a positive integer) in EDI (following the System V AMD64 calling convention used on Gnu/Unix), and returns a single result (the product of divisors) in EAX.
Internally, it computes the product of divisors using an (extremely inefficient) iterative algorithm, similar to pizzapants184's C submission. Basically, it uses a counter to loop through all of the values between 1 and the input value, checking to see if the current counter value is a divisor of the input. If so, it multiplies that into the running total product.
Ungolfed assembly language mnemonics:
; Parameter is passed in EDI (a positive integer)
ComputeProductOfDivisors:
   xor   ecx, ecx        ; ECX <= 0  (our counter)
   lea   esi, [rcx + 1]  ; ESI <= 1  (our running total)
.CheckCounter:
   mov   eax, edi        ; put input value (parameter) in EAX
   inc   ecx             ; increment counter
   cdq                   ; sign-extend EAX to EDX:EAX
   idiv  ecx             ; divide EDX:EAX by ECX
   test  edx, edx        ; check the remainder to see if divided evenly
   jnz   .SkipThisOne    ; if remainder!=0, skip the next instruction
   imul  esi, ecx        ; if remainder==0, multiply running total by counter
.SkipThisOne:
   cmp   ecx, edi        ; are we done yet? compare counter to input value
   jl    .CheckCounter   ; if counter hasn't yet reached input value, keep looping

   mov   eax, esi        ; put our running total in EAX so it gets returned
   ret

The fact that the IDIV instruction uses hard-coded operands for the dividend cramps my style a bit, but I think this is pretty good for a language that has no built-ins but basic arithmetic and conditional branches!

Vyxal, 2 bytes
KΠ

Explanation:
K  # Gets the divisors of a number
 Π # Product of array

Try it Online!

TI-Basic (TI-84 Plus CE), 24 bytes
Prompt X
1
For(A,1,X
If not(remainder(X,A
AAns
End

Full program: prompts user for input; returns output in Ans, a special variable that (basically) stores the value of the latest value calculated.
Explanation:
Prompt X             # 3 bytes, Prompt user for input, store in X
1                    # 2 bytes, store 1 in Ans for use later
For(A,1,X            # 7 bytes, for each value of A from 1 to X
If not(remainder(X,A # 8 bytes, If X is divisible by A...
AAns                 # 3 bytes, ...store (A * Ans) in Ans
End                  # 1 byte, end For( loop

You didn't actually include the bytecount.

@EriktheOutgolfer Whoops! Fixed.

C (gcc), 52 48 bytes
p,a;f(x){for(p=1,a=x;a;a--)p*=x%a?1:a;return p;}

-4 bytes thanks to Cody Gray
A function that takes in an integer and returns the product of it's divisors.
Try it online!
Ungolfed:
int proddiv(int input) {
    int total = 1, loopvar;
    for(loopvar = input; loopvar > 0; --loopvar) {
    // for loopvar from input down to 1...
        total *= (input % loopvar) ? 1 : loopvar;
        // ...If the loopvar is a divisor of the input, multiply the total by loopvar;
    }
    return total;
}

You can save 4 bytes by (1) counting backwards, (2) removing the parentheses around the p*= expression, and (3) putting a statement in the body of the for loop to drop a comma. I also like to use global vars, rather than adding extra parameters. This avoids undefined behavior, without costing any bytes. Final version: p,a;f(x){for(p=1,a=x;a;--a)p*=x%a?1:a;return p;}

You can replace return p; with p=p; and save five bytes.

To save another byte, you can replace p,a;f(x) with f(x,p,a).

If you use local instead of global variables, you can even get rid of the entire return p; and save not five, but nine bytes. (TIO)

45 bytes

JavaScript (ES7), 32 bytes
n=>g=(i=n)=>i?i**!(n%i)*g(i-1):1

Saved a couple of bytes by borrowing Leaky's tip on musicman's Python solution.

Try it

o.innerText=(f=
n=>g=(i=n)=>i?i**!(n%i)*g(i-1):1
)(i.value=1)();oninput=_=>o.innerText=f(+i.value)()
<input id=i type=number><pre id=o>

Alternative (ES6), 32 bytes
n=>g=(i=n)=>i?(n%i?1:i)*g(i-1):1

Why not just the ES6-compatible (n%i?1:i)? (This wouldn't save any byte, though.)

@Arnauld: because half 6 is clearly too early in the morning for phone golf! :D I had the ternary reversed when I spotted Leaky's tip!

TI-Basic, 24 14 13 bytes
Saved 1 byte thanks to lirtosiast
:√(Ans^sum(not(fPart(Ans/randIntNoRep(1,Ans

Do you need the int(?

Shakespeare Programming Language, 353 bytes
.
Ajax,.
Puck,.
Page,.
Act I:.
Scene I:.
[Enter Ajax and Puck]
Ajax:
You cat
Puck:
Listen to thy heart
[Exit Ajax]
[Enter Page]
Scene II:.
Puck:
You sum you cat
Page:
Is Ajax nicer I?If so, is remainder of the quotient Ajax I nicer zero?If not, you product you I.Is Ajax nicer I?If so, let us return to scene II
Scene III:.
Page:
Open thy heart
[Exeunt]

Ungolfed version:
The Tragedy of the Product of a Moor's Factors in Venice.

Othello, a numerical man.
Desdemona, a product of his imagination.
Brabantio, a senator, possibly in charge of one Othello's factories.

Act I: In which tragedy occurs.

Scene I: Wherein Othello and Desdemona have an enlightened discussion.

[Enter Othello and Desdemona]

Othello:
  Thou art an angel!

Desdemona:
  Listen to thy heart.

[Exit Othello]
[Enter Brabantio]

Scene II: Wherein Brabantio expresses his internal monologue to Desdemona.

Desdemona:
  Thou art the sum of thyself and the wind!

Brabantio:
  Is Othello jollier than me?
  If so, is the remainder of the quotient of Othello and I better than nothing?
  If not, thou art the product of thyself and me.
  IS Othello jollier than me?
  If so, let us return to scene II!

Scene III: An Epilogue.

Brabantio:
  Open thy heart!

[Exeunt]

I'm using this SPL compiler to run the program.
Run with:
$ python splc.py product-of-divisors.spl > product-of-divisors.c
$ gcc product-of-divisors.c -o pod.exe
$ echo 30 | ./pod
810000

RProgN 2, 2 bytes
ƒ*

Another language with built ins for divisors and product.
Try it online!

APL (Dyalog Unicode), 7 bytes
-1 byte thanks to @rak1507.
f←×/∘∪⊢∨⍳

Try it online!

Go, 65 64 bytes
func p(n int)int{p,i:=1,1
for;i<=n;i++{if n%i<1{p*=i}}
return p}

Attempt This Online!
Ungolfed

-1 swapping ==0 for <1 (@Steffan)

func product(s []int) int {
	p := 1
	for _,e := range s {
		p *= e
	}
	return p
}
func divisors(n int) (d []int) {
	for i := 1; i <= n; i++ {
		if n % i == 0 {
			d = append(d, i)
		}
	}
	return d
}

Attempt This Online!

You can do n%i<1 instead of n%i==0

QBIC, 22 bytes
[:|~b/a=b'\`a|q=q*a}?q

Explanation
[:|           FOR a  = 1; a <= input (b); a++
 b/a=b'\`a    'a' is a proper divisor if integer division == float division
~         |   IF that's true
q=q*a         THEN multiply running total q (starts as 1) by that divsor
}             NEXT
?q            Print q

Python 2, 52 50 bytes

Thanks @ovs for 2 bytes: m*=n%i>0 or i

i=n=input()
m=1
while i:m*=n%i>0 or i;i-=1
print m

Try it online!

Pari/GP, 18 bytes
n->n^(numdiv(n)/2)

Try it online!

Octave, 27 bytes
@(n)prod(find(~mod(n,1:n)))

This defines an anonymous function.
Try it online!

PHP, 45 bytes
for($p=1;$d++<$argn;)$argn%$d?:$p*=$d;echo$p;

Try it online!

Mathematica, 17 bytes
for those who can't view deleted answers (DavidC's answer), this is the code in Mathematica with the help of @MartinEnder
1##&@@Divisors@#&

Python 3, 45 bytes
lambda _:_**(sum(_%-~i<1for i in range(_))/2)
Let x be a number. Both y and z will be divisors of x if y * z = x. Therefore, y = x / z. Let's say a number d has 6 divisiors, due to this observation the divisors will be a, b, c, d / a, d / b, d / b. If we multiply all these numbers (the point of the puzzle), we obtain d * d * d = d ^ 3. In general, for e with  a number of f divisors, the product of said divisors will be e ^ (f / 2), which is what the lambda does.
Try it online!

Java (OpenJDK 8), 52 51 bytes
n->{int r=n,d=0;for(;++d<n;)r*=n%d<1?d:1;return r;}

Try it online!
Thanks LeakyNun for saving 1 byte!

n->{int r=n,d=0;for(;++d<n;)r*=n%d<1?d:1;return r;}

MY, 4 bytes
Hex:
1A 3A 54 27

Explanation:
1A - Input as an integer
3A - Factors
54 - Product
27 - Output (with newline)

Ruby, 36 bytes
->r{eval (1..r).select{|c|r%c<1}*?*}

Try it online!

Excel VBA, 48 Bytes
Anonymous VBE immediate window function that takes input from range [A1] and outputs to the VBE immediate window
p=1:For i=1To[A1]:p=p*IIf([A1]mod i,1,i):Next:?p

PowerShell Core, 41 40 bytes
param($a)(1..$a|?{!($a%$_)})-join'*'|iex

-1 byte thanks to mazzy!
Try it online!

? Try it online!

x86-64 machine code, 23 bytes
Hexdump:
44 8b c1 6a 01 41 8b c0 99 f7 f9 85 d2 75 04 5a
f7 ea 50 e2 f0 58 c3

Uses the Microsoft calling convention - input in ecx, output in eax. It only supports 32-bit intermediate and final results, to make the code shorter.
Assembly code (can be assembled by ml64):
.CODE
my  PROC
        mov r8d, ecx;   // r8 = input number
        push 1;         // number on stack = product
    myloop:
        mov eax, r8d;   // prepare divisor
        cdq;            // in edx:eax
        idiv ecx;       // divide
        test edx, edx;  // check remainder
        jnz myskip;     // nonzero? - not a divisor
        pop rdx;        // get product from stack
        imul edx;       // multiply
        push rax;       // save product on stack
    myskip:
        loop myloop;    // check next number, down to 0
        pop rax;        // restore stack to proper position
        ret;            // return
my    ENDP
END

I used x64 only for its calling convention - so I would not have to save and restore a general-purpose register - x64 calling conventions permit clobbering r8 and r9.
I used a variant of imul with implicit input and output in eax - it has a shorter encoding (2 bytes), and doesn't require mov to return the result from the function at the end. So it actually multiplies the quotients, not the divisors; the final result remains correct.
Disassembly (to see instruction sizes):
00007FF7F91E1870 44 8B C1             mov         r8d,ecx
00007FF7F91E1873 6A 01                push        1
    myloop:
00007FF7F91E1875 41 8B C0             mov         eax,r8d
00007FF7F91E1878 99                   cdq
00007FF7F91E1879 F7 F9                idiv        eax,ecx
00007FF7F91E187B 85 D2                test        edx,edx
00007FF7F91E187D 75 04                jne         myloop+0Eh (07FF7F91E1883h)
00007FF7F91E187F 5A                   pop         rdx
00007FF7F91E1880 F7 EA                imul        edx
00007FF7F91E1882 50                   push        rax
    myskip:
00007FF7F91E1883 E2 F0                loop        myloop (07FF7F91E1875h)
00007FF7F91E1885 58                   pop         rax
00007FF7F91E1886 C3                   ret

Husk, 2 bytes
ΠḊ

Try it online!
builtins.

Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes
*rk

Try it online!
Multiplication analog of the addition version.

Prolog (SWI), 60 bytes
A+N+S:-A>0,A-1+N+Q,(N mod A<1,S is Q*A;S=Q);S=1.
N+S:-N+N+S.

Try it online!

Pyt, 2 bytes
ðΠ

Try it online!
ð       implicit input; get list of divisors
 Π      product of list; implicit print

Thunno 2, 2 bytes
Fp

Try it online!
Explanation
Fp  # Implicit input
F   # Factors
 p  # Product
    # Implicit output

Perl 6, 22 bytes
{[*] grep $_%%*,1..$_}

Try it online!

J, 19 bytes
*/}.I.(=<.)(%i.@>:)

Explanation coming later...
Try it online!

Fortran 95, 88 bytes
function l(k)
n=0
l=1
do while(n<k)
n=n+1
if(MODULO(k,n)==0)then
l=l*n
end if
end do
end

Try it online!
Ungolfed:
integer function l(k)
    implicit none
    integer :: n, k

    n=0
    l=1
    do while (n<k)
        n=n+1
        if (MODULO(k,n) == 0) then
            l=l*n
        end if
    end do

end function l

Axiom, 23 bytes
h(x)==x^(#divisors x/2)

This is a translation in Axiom of alephalpha solution

Arn, 3 bytes
Þ┤â

Try it!
Explained
Unpacked: *\*.
*\ fold with multiplication
*. a list of factors of the input

Julia, 27 bytes
f(x,y=1:x)=prod(y[x.%y.<1])

Try it online!

MathGolf, 3 bytes
─ε*

Try it online.
Explanation:
─    # Get a list of divisors of the (implicit) input-integer
 ε   # Reduce this list by:
  *  #  Subtracting
     # (after which the entire stack joined together is output implicitly as result)

SageMath, 24 bytes
f=compose(prod,divisors)

Straightforward and direct. Is there a shorter way to do it in Sage?

Perl 5 -ap, 31 bytes
map$.*="@F"%$_?1:$_,2..$_;$_=$.

Try it online!

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


text:
Sort a list without builtin functions
Your task will be to write a Haskell function that takes a list of integers and returns a sorted version of the same list.  You are to do this without the use of builtins
What are builtins?
To keep ourselves from having to navigate edge case hell we are going to limit answers to Haskell (sorry if Haskell is not your favorite language). We are going to define a builtin as any named function that is not defined in your code.  We are going to say that symbolic operators, (+), (:), etc. are not builtin functions.  This applies both to prelude and any libraries that are imported.
What does it mean to use?
Before anyone tries to get smart with me, using a function is using a function.  Whether or not the function is named in your source code is irrelevant (this is not restricted-source), if you make calls to the function without naming it that is also considered cheating.  That being said calls to a function are not the only form of use, you shouldn't name a builtin function in your code even if you don't call it (I don't know why you would want to do that but I'm not taking any risks).
Scoring
This is code-golf so you should aim to do this in as few bytes as possible.  However since different algorithms are not going to be competitive, (merge sort answers are probably going to be longer than insertion sort answers) I would like this to be considered a competition among individual algorithms, just as normal code golf is a competition among individual languages.  For that reason I would like you to name your algorithm used in your header instead of the language.  If you don't know the name feel free to put Unknown.

Related (sort list without sort builtin)

I would have upvoted this if the challenge was not limited to a specific language.

@KritixiLithos I would have like to made it open to all languages, however the definition of builtin would have needed to be extremely complex.  I figured it was best to constrain it to one language rather than have a broken challenge.  Maybe I should have not asked the question.  But I think its pretty fun if you give it a try.

as we are talking about Haskell only, what about builtin values?

@WheatWizard Idea: allow other languages to join in but they are marked as NC

@nimi I think builtin values are fine.

@Christopher The problem with other languages is that the challenge gets very out of control and the definition becomes untenable, not that I don't like them.  I don't think allowing NC answers would improve the challenge.

@WheatWizard I think that if you allow functional programming languages that aren't designed for golfing (e.g. Python, Java, C etc.) where the definition of a builtin matches your current one, then the challenge would be better. If you do this, however, I would recommend having a list of languages which people can suggest changes to.

@cairdcoinheringaahing Believe it or not this was originally a python challenge, but I found it too difficult to get a good definition of builtin with member functions.  I would also like to point out that none of the three languages you mentioned are functional :P, but I suppose that doesn't matter.

Sorry, Wheat but I've downvoted this for the language restriction. The shame about it is that it would be an interesting challenge otherwise.

@Shaggy If you or anyone would like to post a version that is open to all languages they are free to do so.  However it is my belief that such a challenge would turn out rather poorly and I am very satisfied with the current answers so I will not be opening this challenge to additional languages.  I've already expressed why I believe this in previous comments so I won't go into further detail.

Haskell, 57 56 37 33 bytes
f l=[y|x<-[minBound..],y<-l,y==x]

Feed it with Ints, e.g. f [1::Int,2,3].
A port of my answer from the other sort without builtin challenge which supports also lists with repeated values.
Edit: @Ørjan Johansen saved 4 bytes. Thanks!

That fix is quite clever.

@WheatWizard: it loops through all Ints, which takes some time. For a test you can go with f l=[-10..10]>>= \x->[y|y<-l,y==x] and limit the range of the element of the list to sort accordingly. -- or sort small values: f [-2^63+1::Int,-2^63,-2^63+1]

I see.  Congratulations, It look like you have figure out a way to sort a list in O(n) :P

This is 4 bytes shorter as a big list comprehension: f l=[y|x<-[minBound..],y<-l,y==x]

@ØrjanJohansen: well spotted! Thanks a lot!

Mergesort, 110 bytes
x@(a:r)#y@(b:s)|a<b=a:r#y|1<3=b:x#s
r#s=r++s
(x:r)!(a,b)=r!(b,x:a)
_!t=t
s[x]=[x]
s l|(a,b)<-l!([],[])=s a#s b

Try it online! Example usage: s [4,1,26,-3,0,5].
# takes two sorted lists and merges them. ! splits a list in two sublists of equal length. s returns singleton lists unchanged because they are already sorted and sorts longer lists by splitting them in two parts, recursively sorts both and merges the resulting lists.

Insertion Sort, 44 bytes
s!(a:b)|a<s=a:s!b
s!x=s:x
f(a:x)=a!f x
f a=a

Try it online!
Since nimi has already outgolfed me I thought I would post the solution I came up with to my own challenge.
Explanation
Here we define a function (!) that takes a sorted list and inserts an element so that the list is still sorted.
s!(a:b)|a<s=a:s!b
s!x=s:x

We then define a function f that takes sieves the elements of a list into this function.  (basically the equivalent of a foldr).
f(a:x)=a!f x
f a=a

Since the empty list is sorted, and each insertion keeps the list sorted, the end result is a sorted list with all the same items as the original.  This algorithm is O(n2).

Quicksort (sort of), 44 bytes
s(h:t)=s[e|e<-t,e<=h]++h:s[e|e<-t,e>h]
s x=x

Try it online!
How it works:
s(h:t)=               -- let h be the head and t the rest of the input list
        [e|e<-t,e<=h] -- take all elements e from t that are less or equal than h
       s              -- and sort them recursively
          ++ h :      -- append h and append
        [e|e<-t,e>h]  -- all elements from t greater than h
       s              -- after sorting them
s x=x                 -- base case: if there's no first elemet, i.e. the list
                      -- is empty, the result is also the empty list

Here's a shorter merge sort, bottom up, called s. ((:[])<$>) divides up the list into singletons (turning "Joe" into ["J","o","e"]). d merges adjacent pairs of lists, using the basic merge function !. f iterates d until there's only one list.
Merge sort, 99 bytes
s=f.((:[])<$>)
a@(x:y)!b@(z:w)|x>z=z:a!w|0<1=x:y!b
a!b=a++b
d(x:y:z)=x!y:d z
d p=p
f[x]=x
f x=f$d x

Try it online!

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


text:
Maximum number of distinct substrings
Description
Given a length n, and an alphabet size k>0, your program must determine the number of strings with those parameters which have a maximal number of unique substrings. In the case of k=2, this generates OEIS A134457.
Example
For example, 2210 has the substrings   , 2, 22, 221, 2210, 2, 21, 210, 1, 10, and 0, for a total of 11. However, 2 appears twice, so it only has 10 unique substrings.
This is as many as possible for a length 4 string containing 3 different symbols, but it ties with 35 other strings for a total of 36 tieing strings including 0012, 2101, and 0121. Therefore, for n=4 and k=3, your program should output 36.
Test Cases
n    k    output

0    5    1
1    3    3
5    1    1
9    2    40
2    3    6
5    5    120

Could you please give some examples? It's kind of hard to follow the challenge from that very short description.

So wouldn't n=2, k=3 output 9: 11,12,21,22,31,32,33,13,23?

@veganaiZe The double digits have a repeated substring.

Jelly, 9 bytes
ṗµẆQLµ€ML

Try it online!
Input in reversed order. Brute force.

Save a byte by avoiding the three-atom chain with a transpose and tail: ṗẆQ$€ZṪL

Pyth, 12 bytes
l.Ml{.:Z)^UE

Try it online.
Pure brute force.
Explanation

Implicit: append Q to the program.
Implicit: read and evaluate a line of input (n) in Q.
E: read and evaluate a line of input (k).
U: get a range [0, ..., k-1].
^: get all n-length strings of [0, ..., k-1].
.M: find the ones that give a maximum for function f(Z):

.:Z: find the substrings of Z
{: remove duplicates
l: get the number of unique substrings

l: get the number of such strings

Mathematica, 96 bytes
Last[Last/@Tally[Length@Union@Flatten[Table[Partition[#,i,1],{i,s}],1]&/@Tuples[Range@#2,s=#]]]&

Haskell, 82 bytes
import Data.Lists
l=length
n#k=l$argmaxes(l.nub.powerslice)$mapM id$[1..k]<$[1..n]

Usage example: 9 # 2 -> 40.
How it works:
       [1..k]<$[1..n]  --  make a list of n copies of the list [1..k]
      mapM id          --  make a list of all combinations thereof, where
                       --  the 1st element is from the f1st list, 2nd from 2nd etc
  argmaxes             --  find all elements which give the maximum value for function:
     l.nub.powerslice  --    length of the list of unique sublists
l                      --  take the length of this list


text:
Is it a weak prime?
A prime is weak if the closest other prime is smaller than it.  If there is a tie the prime is not weak.
For example 73 is a weak prime because 71 is prime but 75 is composite.
Task
Write some computer code that when given a prime greater than 2 as input will determine if it is a weak prime.  This is a standard decision-problem so you should output two unique values for each of the two cases (e.g. weak and not weak).
This is code-golf so standard rules for the tag apply.
OEIS
Here are the first 47 weak primes:
3, 7, 13, 19, 23, 31, 43, 47, 61, 73, 83, 89, 103, 109, 113, 131, 139, 151, 167, 181, 193, 199, 229, 233, 241, 271, 283, 293, 313, 317, 337, 349, 353, 359, 383, 389, 401, 409, 421, 433, 443, 449, 463, 467, 491, 503, 509, 523, 547, 571, 577, 601, 619, 643, 647

Here is the OEIS for weak primes (should return weak) OEIS A051635
Here is the OEIS for balanced primes (should return not weak) OEIS A006562
Here is the OEIS for strong primes (should return not weak) OEIS A051634

not weak or strong?

@CalculatorFeline not weak is different than strong

Jelly, 7 bytes
Æn+Æp>Ḥ

Try it online!
Explanation
           See if
Æn         the next prime
  +Æp      plus the previous prime
     >Ḥ    is greater than 2n

As a bonus, changing > to  = or < checks for balanced and strong primes, respectively.

That should be >, no?

Oh wow, that's clever...

I just worked this way out too. Nice work!

This is so clever...

Mathematica, 24 bytes
n=NextPrime;2#+n@-#<n@#&

The NextPrime built-in can be (ab?)used to compute the previous prime by feeding it a negative argument.

Jelly, 9 bytes
ḤÆRạÞ⁸ḊḢ>

Returns 1 for weak and 0 for not weak or balanced (returns 1 for an input of 2)
Try it online!
How?
ḤÆRạÞ⁸ḊḢ> - Link: prime number > 2, p
Ḥ         - double -> 2*p
 ÆR       - yield primes between 2 and 2*p inclusive
     ⁸    - chain's left argument, p
    Þ     - sort by:
   ạ      -   absolute difference (i.e. distance from p)
      Ḋ   - dequeue (removes p from the list, since it has distance zero)
       Ḣ  - head (gives us the nearest, if two the smallest of the two)
        > - greater than p?

Ninja'd me with a complex solution...

It was a split-second!

No it wasn't, it was 9 full seconds iirc. No, 10 seconds.

So it was (looking at the times) it happened as I submitted here :)

Well, it seems you just golfed faster than me...(it's quite a trip to first go from IIṠ⁼1 to II>0 to I<\)...yours is much different though. It seems you think differently than me...EDIT: Pietu1998 returned!

PHP, 69 bytes
prints one for weak prime and nothing for not weak prime

for(;!$t;$t=$d<2)for($n=$d=$argn+$i=-$i+$w^=1;$n%--$d;);echo$n<$argn;

Try it online!

Octave, 93 84 bytes
Thanks to @LuisMendo and @rahnema1 for saving bytes!
function r=f(x);i=j=x;do--i;until(i<1|isprime(i));do++j;until(isprime(j));r=x-i<j-x;

Try it online!

Can't you use i-=1 etc? Also, end is not needed in the function; you can move it to the footer

MATL, 13 bytes
qZq0)G_Yq+GE>

This outputs 1 if weak, 0 otherwise.
Try it online!
Explanation
q      % Implicit input, Subtract 1
Zq     % Vector of primes up to that
0)     % Get last one
G      % Push input again
_Yq    % Next prime
+      % Add
G      % Push input
E      % Multiply by 2
>      % Greater than? Implicit display

Maxima, 42 bytes
f(n):=is(n-prev_prime(n)<next_prime(n)-n);

Try it online!

GNU APL 1.2, 78 bytes
∇f N
X←(R←(~R∊R∘.×R)/R←1↓⍳N×2)⍳N
(|R[X-1]-N)<|R[X+1]-N
∇

∇f N declares a function that takes an argument.
(~R∊R∘.×R)/R←1↓⍳N×2 gives a list of all the primes from 2 to twice the argument. I'm assuming that the next prime is less than twice the original. If this is untrue, N*2 gives N squared and takes the same number of bytes (hopefully that's big enough to exceed the next prime). (See Wikipedia's explanation for how the prime-finding works)
X←(R←(...))⍳N assigns that list to vector R (overwriting its previous contents), finds the index of the original prime N in that list, and then assigns that index to X.
|R[X-1]-N computes the difference between the previous prime (because R contains the primes, the X-1th element is the prime before N) and N and then takes the absolute value (APL operates right-to-left).
|R[X+1]-N does the same, but for the next prime.
(|R[X-1]-N)<|R[X+1]-N prints 1 if the previous prime is closer to the original than the next prime and 0 otherwise. Parentheses are needed for precedence.
∇ ends the function.

Jelly, 9 bytes
Æp;;ÆnI</

Try it online!

Pyth, 15 bytes
>-fP_ThQfPT_tQy

Try it here.
Uses Pietu1998's algorithm.

Perl 6, 41 bytes
{[>] map ->\n{$_+n,*+n...&is-prime},1,-1}

Try it online!
$_ is the argument to the function.  The mapping function -> \n { $_ + n, * + n ... &is-prime } takes a number n and returns a sequence of numbers $_ + n, $_ + 2*n, ... that ends when it reaches a prime number.  Mapping this function over the two numbers 1 and -1 produces a sequence of two sequences; the first starts with $_ + 1 and ends with the first prime number greater than $_, and the second starts with $_ - 1 and ends with the first prime number less than $_.  [>] reduces this two-element list with the greater-than operator, returning true if the first sequence is greater (ie, longer) than the second.

Python 2, 122 108 103 94 92 bytes
def a(n):
 r=[2];x=2
 while r[-1]<=n:x+=1;r+=[x]*all(x%i for i in r)
 return sum(r[-3:])>3*n

Try it online!
Uses Pietu's idea... and then saved 28 bytes by golfing shorter prime list iterators; then 2 more by replacing -3*n>0 with >3*n (d'oh!)

Python 2.7 - 120 bytes
from math import*
i=lambda x:factorial(x-1)%x==x-1
def f(n,c):return 1 if i(n-c)>i(n+c) else 0 if i(n+c)>0 else f(n,c+1)

Since python doesn't have a built-in is prime function, we can use Wilson's theorem to get a nice short prime checker. Wilson's theorem states that a number is prime if and only if (n-1)! is congruent to -1 mod(n). Hence the function i will return 1 if the number is prime and 0 if it's not. Following that the f function will determine if the next prime from that number occurs first when incremented down rather than incremented up. If neither of the incremented numbers prime, it's just recursively called again.
Some example I/O
f(3,1)
1
f(15,1)
0

Regex (most flavors), 47 bytes
^(?=(x*)(?!(x+)(\2\2x)+$)\1)x+(?!(xx+)\4+$)\1\1

Try it online!
Takes input in unary. Outputs a match for weak primes, no match for non-weak primes. Works in ECMAScript, Perl, PCRE, Python, Ruby.
Explanation:
Let N be the input, A the closest prime < N, and B the closest prime > N. The main difficulty of a regex approach to this challenge is that we can’t represent numbers greater than the input, like B. Instead, we find the smallest b such that 2b + 1 is prime and 2b + 1 > N, which ensures 2b + 1 = B.
(?=
  (x*)              # \1 = N - b, tail = b
  (?!(x+)(\2\2x)+$) # Assert 2b + 1 is prime
  \1                # Assert b ≥ \1 (and thus 2b + 1 > N)
)

Then, note that we don’t actually need to find A. As long as any prime < N is closer to N than B, N is a weak prime.
x+                  # tail iterates over integers < N
(?!(xx+)\4+$)       # assert tail is prime
\1\1                # assert tail ≥ 2 * \1 (and thus tail + B > 2N)

Octave, 53 bytes
@(n)diff(list_primes(h=nnz(primes(n))+1)(h-2:h),2)>0

Try it online!

JavaScript ES6, 162 154 bytes
8 bytes save based on Jörg Hülsermann's trick "print nothing in one case". No need to ?"Y":"N" after one<two

var isWeak=

a=>{p=[2];i=0;f=d=>{j=p[i];l:while(j++){for(x=0;p[x]*p[x]<=j;x++){if(j%p[x]==0){continue l}}return p[++i]=j}};while(p[i]<a+1){f()};return a*2
{console.log(n,isWeak(n))})

05AB1E, 17 bytes
[<Dp#]¹[>Dp#]+¹·›

Try it online!
Uses Pietu1998's algorithm.

Python 3, 149 bytes
f=lambda n,k=1,P=1:n*[0]and P%k*[k]+f(n-P%k,k+1,P*k*k)
def a(n):p=f(n);return p.index(n)in filter(lambda i:p[i]-p[i-1]
0$+L[->+>2[>q[#:Q]]]

Walkthrough:
;                       Read a number to cell 0
 >0$+                   Go to cell 1 and copy the value of cell 0
     L                  Make the tape wrap around after cell 1
      [              ]  Loop:
       ->+>               Decrease cell 1 and increase cell 0
           2[       ]     Twice do:
             >              Go to the other cell
              q[   ]        If it's prime:
                #:Q         Print the current cell number and quit

JavaScript, 98 bytes

let test = _=>(o.innerHTML=f(+prime.value))
let f=

n=>{P=n=>{for(i=n,p=1;--i>1;)p=p&&n%i};a=b=n;for(p=0;!p;P(--a));for(p=0;!p;P(++b));return n-a<b-n}
Enter Prime: <input id="prime">
<button type="button" onclick="test()">test if weak</button>

Less Golphed
n=>{
   P=  // is a Prime greater than 1, result in p
       n=>{
           for(i=n,p=1;--i>1;)
               p=p&&n%i
       };

   a=b=n; // initialize lower and upper primes to n
   for(p=0;!p;P(--a)); // find lower,
   for(p=0;!p;P(++b)); // find upper,
   return n-ag(x,1)&(g(x-1,-1)<g(x+1,1))

Python 2, 81 bytes
n=input()
a=b=c=i=2;p=1
while b<n:
 p*=i;i+=1
 if p*p%i:a,b,c=b,c,i
print a+c>2*b

Try it online!
Uses Wilson's theorem for the primality test.

Husk, 15 bytes
>D¹Σ§e₁←₁→
ḟṗt¡

Try it online!


text:
Fibtraction - Fibonacci but with subtraction
The Fibtraction sequence (as I call it) is similar to the Fibonacci sequence except, instead of adding numbers, you subtract them.
The first few numbers of this challenge are:
1, 2, -1, 3, -4, 7, -11, 18, -29, 47, -76, 123, -199, 322, -521, 843, -1364...

The sequence starts with 1 and 2. Every next number can be calculated by subtracting the previous number from the number before it.
1
2
-1 = 1 - 2
3  = 2 - (-1) = 2 + 1
-4 = -1 - 3
7  = 3 - (-4) = 3 + 4
...

In other words:
f(1) = 1
f(2) = 2
f(n) = f(n - 2) - f(n - 1)

This is OEIS sequence A061084.
Challenge
Write a program/function that takes a positive integer n as input and prints the nth number of the Fibtraction sequence.
Specifications

Standard I/O rules apply.
Standard loopholes are forbidden.
Your solution can either be 0-indexed or 1-indexed but please specify which.
This challenge is not about finding the shortest approach in all languages, rather, it is about finding the shortest approach in each language.
Your code will be scored in bytes, usually in the encoding UTF-8, unless specified otherwise.
Built-in functions that compute this sequence are allowed but including a solution that doesn't rely on a built-in is encouraged.
Explanations, even for "practical" languages, are encouraged.

Test cases
These are 0-indexed.
Input      Output

1          2
2          -1
11         123
14         -521
21         15127
24         -64079
31         1860498

That pattern was totally not intentional. :P
This challenge was sandboxed.

Before you go pressing any buttons that do scary things, hear me out. This might be considered a dupe of the regular Fibonacci challenge and I agree, to some extent, that it should be easy enough to port solutions from there. However, the challenge is old and outdated; is severely under-specified; allows for two types of solutions; has answers that don't have easy ways to try online; and in general, is lacking of answers. Essentially, in my opinion, it doesn't serve as a good "catalogue" of solutions.

plz send teh codez

Note that after the first two terms it devolves into the Lucas sequence with alternating signs.

i could close this as a dupe of other Lucas number challenges but not having enough online executable answers is not reason to not be dupe. We could have a discussion about making that challenge clearer but it is still dupe regardless

Even if the old Fibonacci challenge has some shortcomings and doesn't serve it's purpose as a catalogue very well, the best solution would be to make a good, canonical Fibonacci challenge, not an almost-Fibonacci challenge, because no one will look for that as a repository of Fibonacci solutions. Before you do though, this should probably be brought up on meta. We've discussed retiring the old Fibonacci challenge a couple of times, and I think Chris said he'd be fine with it, but I'm not sure what to do with all the answers that do work there.

Okay, should I write a meta post? I strongly believe we should have a good "repository" of solutions for one of our most basic challenges.

Is this exactly similar to the regular Fibonacci sequence? If we say the first term of the Fibonacci sequence is 1, then second is also 1(0th term = 0 + 1). By that logic, this sequence should be 1, -1, 2, -3, 5, -8, 13, .....

Yeah, the Fibonacci sequence either starts with 1 and then adds/subtracts (leading to cst1992's solution) or starts with 1,1 (so then goes 0, 1, -1, 2, -3... and is thus also the Fibonacci sequence, albeit delayed by three places). Defining this as starting with 1, 2 seems... dubious.

I voted to close this challenge. If we want to make a proper catalog for the Fibonacci sequence that has a well-defined specification, then I think it should be for the vanilla Fibonacci sequence and not a manipulation of it. The challenge this is a dupe of is a better candidate in my opinion.

I marked this as a duplicate to "lock" the question and answers while the Meta question is sorted out. Thanks.

Oasis, 4 bytes
c-21

Try it online!
0-indexed.
I saw this language used for a similar challenge once, and immediately I knew I should try it here. Can't say I'm disappointed.
Explanation
   1    a(0) = 1
  2     a(1) = 2
c       a(n) = a(n - 2)
 -                      - a(n - 1)

I saw this challenge with only 1 answer and figured I could get an Oasis answer in. 2 seconds later you did it. Nice :P

Oh, wow, I'm a dumbass; I thought the chat was "05AB1E Oasis" as in a cool place to lounge. Little did I know it was a language.

Python 2, 35 34 bytes
 -1 byte thanks to ovs!
f=lambda n:n*(n<3)or f(n-2)-f(n-1)

Try it online!
Answers are 1-indexed. Takes advantage of f(2) and f(1) being equal to their respective inputs.

Javascript, 24 bytes
f=n=>n<3?n:f(n-2)-f(n-1)

f=n=>n<3?n:f(n-2)-f(n-1)

for (let i = 1; i <= 20; i++) {
  console.log(f(i))
}

Octave, 27 bytes
0-indexed.
@(n)([1,2]*[0,1;1,-1]^n)(1)

Try it online!

Very nice approach!

How does this work?

Haskell, 29 26 bytes
Inspired by alephalpha's answer I thought, I'd derive an explicit formula. It's been a while since I did an Eigenvalue decomposition, turns out the explicit formula (even after golfing it down) is longer and fails because of floating point issues.
0-indexed:
(g!!)
g=1:scanl(flip(-))2g

Try it online!
Saved 3 bytes thanks to @Laikoni
Decomposition solution, 48 bytes
There are a couple eigenvector decompositions; the simplest is actually -1-indexed rather than 0-indexed or 1-indexed:
Prelude> map (\n -> ((-1 + sqrt 5)/2)**n + ((-1 - sqrt 5)/2)**n) [0..10]
[2.0,-1.0,3.0,-4.0,7.0,-11.0,18.0,-29.000000000000004,47.0,-76.0,123.0]

Since the (-1 + sqrt 5)/2 term is less than 1, we can absorb that into the needed round at the cost of adding some leading terms,
Prelude> [round$((-1 - sqrt 5)/2)^n|n<-[0..10]]
[1,-2,3,-4,7,-11,18,-29,47,-76,123]

So e.g. one can get to a function by, but this is not much-more golfable and it's 48 bytes:
((1:2: -1:[round$(-(1+sqrt 5)/2)^n|n<-[2..]])!!)

Try it online!

You can drop the space in 2 g. Also anonymous functions are allowed, so you do not need the f=.

Whoops, thanks! I thought about the anonymous function too, but then I have a naked expression in the code. Is this ok?

That's fine, see the Guide to golfing rules in Haskell. For TIO you can either keep the f= or use this tip.

I think the most I can golf the explicit formula is the 48-byte ((1:2: -1:[round$(-(1+sqrt 5)/2)^n|n<-[2..]])!!), or subtract 6 bytes if the list is ok as output.

@CRDrost Yeah it's pretty much ungolfable (at least wrt. to the other solution). Feel free to create your own answer or edit it in, if you like.

x86 Machine Code, 12 bytes
Iterative solution; 0-indexed
31 C0
40
8D 50 01
29 D0
92
E2 FB
C3

The above function takes a single input, n (passed in the ECX register, following Microsoft's fastcall calling convention), and returns the nth number of the Fibtraction sequence in the EAX register.
The implementation is based on the well-known trick for calculating a Fibonacci number using two variables, which Snowman's answer in Java reminded me of.
Not only is this solution much smaller in size than my first attempt (it even competes with Mathematica using a built-in), it will also be much faster because it is iterative, rather than recursive. Theoretical comp-sci's love for recursion is foiled once more!
Ungolfed assembly mnemonics:
Fibtraction:
   xor  eax, eax
   inc  eax                ; EAX = 1  (XOR+INC are 3 bytes; same as PUSH+POP)
   lea  edx, [eax + 1]     ; EDX = 2  (LEA is 3 bytes; same as PUSH+POP)
Iterate:
   sub  eax, edx           ; EAX = EAX - EDX
   xchg eax, edx           ; swap EAX and EDX
   loop Iterate            ; decrement ECX and keep looping as long as ECX != 0
   ret                     ; return, with result in EAX

Try it online!
A couple of things worth pointing out here…

We start by loading the constants 1 and 2 into registers. These are our starting values. The standard way, of course, to load constants into registers is mov reg, imm. That's fast, but it takes a whopping 5 bytes to encode. So, for code-golfing purposes, we make use of various other tricks to load values into registers. A 2-byte PUSH that pushes the immediate value onto the stack, followed by a 1-byte POP that pops the value off the top of the stack and into a register, is the workhorse trick—very common and very useful. But, if you are just setting the register to 1, you can do XOR+INC, which is the same 3 bytes. And, if you already have the value you want in a register, then you can build off of it using the magic LEA instruction, which is also only 3 bytes. Both of those tricks are showcased here, since they are more interesting and somewhat faster than the good old PUSH+POP.
Inside of the body of the loop, we do a pretty neat optimization. The fundamental operation we're doing here is:
edx = (eax - edx)
eax -= edx

which would naively be translated to (indeed, this is what most C compilers do):
sub  eax, edx                              ; 2 bytes
mov  ebx, edx                              ; 2 bytes
mov  edx, eax                              ; 2 bytes
mov  eax, ebx                              ; 2 bytes

or, somewhat better—rewrite the subtraction as addition of a negative so that the operand order can be reversed, allowing the result to end up in the desired register without having to clobber a temporary register (ICC is able to apply this optimization):
neg  edx                                   ; 2 bytes
add  edx, eax     ; edx = (eax - edx)      ; 2 bytes
sub  eax, edx     ; eax -= edx             ; 2 bytes

but I have written it as:
sub  eax, edx                              ; 2 bytes
xchg eax, edx                              ; 1 byte

which is conceptually similar to the naive version (only one subtraction is done, then some moves), but much more compact because of the XCHG instruction. This avoids clobbering a register, and decreases the size of the code. (I guess you could have equally well used an XOR to avoid clobbering a register—the famous move-without-a-temporary trick—but XCHG is 1 fewer byte for golfing purposes.)
Now, to be fair, the MOVs are probably much faster in real-world code, especially on modern processors that can elide moves in the front end via register renaming. Exchanges can't be elided, and aren't known for being particularly fast. If it weren't for register renaming, ICC's code (the add-a-negative approach) would probably be the fastest in the real-world, since it's compact and arithmetic operations are extremely efficient.
The LOOP instruction. This is an old CISC-style instruction that is equivalent to:
dec  ecx
jnz  Label

but is avoided in modern code (and by all compilers) because it's actually slower than the above sequence. It's also less versatile, because it has the ECX register hard-coded as the counter. However, for code-golf purposes, it's great! And since we used a calling convention that passes the parameter in ECX, we don't even have to do anything!
(If you wanted to use a different calling convention, you'd just have to do a MOV or XCHG at the very top of the function to copy the parameter into ECX; or, you could swap out the LOOP instruction for the expanded form shown above. Either of these would only cost a couple of bytes, maximum, so this optimization isn't really saving us much, but I think it does earn a couple of style points! :-)

Similarly, if you wanted to write this for x86-64, like my original answer, which uses a different calling convention, it would be easy to adapt. Either of these will do it, and both are only 14 bytes:
Fibtraction_64_A          |      Fibtraction_64_B:
   push 1                 |         mov  ecx, edi
   pop  rax               |         push 1
   lea  edx, [rax+1]      |         pop  rax
Iterate:                  |         lea  edx, [rax+1]
   sub  eax, edx          |      Iterate:
   xchg eax, edx          |         sub  eax, edx
   dec  edi               |         xchg eax, edx
   jg   Iterate           |         loop Iterate
   ret                    |         ret

+1 for the very detailed explanation. Is there a way to run this code on TIO?

@cows As it turns out, yes. I just didn't know how to do it at the time I wrote this answer. I've added in a link. The trick uses a C wrapper to call the assembly code. There is an assembler on TIO, but screen output is platform-specific (and often requires a lot of code in asm), so doing it that way is a much bigger pain, which is why I used to avoid it.

05AB1E, 7 bytes
3XIFDŠ-

Try it online!
Explanation
3         # push 3
 X        # push 1
  IF      # input times do:
    D     # duplicate top of stack
     Š    # move the copy down 2 spaces on the stack
      -   # subtract top 2 numbers

Fails for 0 :(

@Datboi: Thanks for notifying! Fortunately it was easily fixed without costing any bytes :)

Oh wow. I was looking for a fix myself and the best I could come up with was 11 bytes but you just did it without using any more bytes :D gratz

cQuents, 8 bytes
=1,2:y-z

1-indexed. Since cQuents isn't stack based it isn't as terse as Oasis. Prints the whole sequence if no input is given.
Try it online!
Explanation
=1,2      Sequence start equals 1,2
    :     Mode: sequence. Prints the 1-indexed nth term for input n.
     y-z  Each item in the sequence equals the second to last item minus the last item

Note current version uses Y and Z instead of y and z

Jelly, 5 bytes
1_@¡3

0-indexed.
Try it online!

Perl 6, 19 bytes
{(1,2,*-*...*)[$_]}

test it
Expanded:
{  # bare block lambda with implicit parameter ｢$_｣
  (

    1, 2,  # seed the sequence

    * - *  # WhateverCode lambda used to generate the rest of the values

    ...    # keep generating until:

    *      # never stop

  )[ $_ ]  # index into the sequence
}

If it was f(n) = f(n - 1) - f(n - 2) it would be {(1,2,*R-*...*)[$_]} instead

Mathematica (using a built-in), 18 12 bytes
Several bytes saved by user202729 !
LucasL[2-#]&

Or the same idea without a built-in, for 32 31 30 29 bytes:
Tr[{p=(1+5^.5)/2,1-p}^(2-#)]&

Uses 1-indexing. Try them at the Wolfram sandbox (they don't work in Mathics, unfortunately).
This uses the observation by ETHproductions and user202729 that the sequence is nearly the Lucas numbers (only with alternating sign, or reading backwards). The 29-byte function is the closed formula for the Lucas numbers.

I think that is LucasL[1-#]& or something. I didn't test...

Mathics, 31 bytes
f@1=1
f@2=2
f@x_:=f[x-2]-f[x-1]

-2 thanks to @MartinEnder!
Try it online!

The first two definitions can use = instead of := and it's shorter to define an operator ± instead of a function f, because you save the @s in the definitions. (I'm not sure the latter works in Mathics, but it would in Mathematica.)

@MartinEnder thanks! I tried it with just = earlier but it didn't seem to work.

The overall shortest approach is to use an unnamed function though: If[#<3,#,#0[#-2]-#0[#-1]]&

@MartinEnder it uh... Doesn't work in mathics due to garbage Unicode support. Welp.

You can post that answer, if you want.

Brainfuck, 51 44 bytes
+++++>+>++<<[>[>>+<<-]>[<+>>-<-]>[<+>-]<<<-]

0-indexed, the input is on cell 0 and the output on cell 1.
Output is in two complement format.
Per this meta consensus, input for Turing machines may be written to the tape pre-execution, and the contents of the tape post-execution may be used as a Turing machine's output.
How?
# The tape: I O A B . . .
# I = input, O = output

>+     # O = 1
>++    # A = 2
<<[
    >[>>+<<-]     # B = O              [ I   0   A   O  ]
    >[<+>>-<-]    # B = B - A, O = A   [ I   A   0  O-A ]
    >[<+>-]<<<    # A = B = O - A      [ I   A  O-A  0  ]
-]     # Repeat I times

Brainfuck is Brainfuck, not a Turing Machine.

Can we have a TIO link?

@Phoenix What's with that comment? It is anyway similar to a Turing machine, but lack random IP move. So it can be a subset of Turing machine (yet still Turing complete)

PHP, 45 bytes
0-indexed

for($x=1,$y=2;$argn--;)$x=$x-$y=$x-$y;echo$x;

Try it online!
PHP, 46 bytes
1-indexed recursive function

function f($i){return$i<3?$i:f($i-2)-f($i-1);}

Try it online!

Java, 65 61 bytes
Golfed:
n->{int a=1,b=2;for(;n-->0;a-=b)b=a-b;System.out.println(a);}

This uses the standard trick of calculating Fibonacci using only two variables to hold the state, but modified to work with subtraction. I am aware that theoretically, System.out.print() should work here but in practice it is inconsistent with flushing output and sometimes (often enough to be an issue) will literally print nothing using the Oracle JVM.
This function is zero-indexed.
Try it online!
Ungolfed:
public class FibtractionFibonacciButWithSubtraction {

  public static void main(String[] args) {
    for (int i : new int[] { 1, 2, 11, 14, 21, 24, 31 }) {
      f(n -> {
        int a = 1, b = 2;
        for (; n-- > 0; a -= b)
          b = a - b;
        System.out.println(a);
      } , i);
    }
  }

  private static void f(java.util.function.Consumer<Integer> function, int n) {
    function.accept(n);
  }
}

You can use for(;n-->0;a-=b)b=a-b; instead of for(;n>0;--n){b=a-b;a-=b;} to save 4 bytes.

C, 30 bytes
Try Online 1-indexed
s;f(n){s=n>2?f(n-2)-f(n-1):n;}

Is it acceptable to return the value through an external variable? I'm not very sure.

@KeyuGan the value is returned, one way or another, but consider this, this function does return the value of s with some compilers, try tcc on TIO

@Khaled.K Astonishing! I used to think f(a){a=1;} in GCC return 1 is weird enough. But tcc proves to be more interesting.

Pari/GP, 26 bytes
n->([1,2]*[0,1;1,-1]^n)[1]

Try it online!

Common Lisp, 46 bytes
(defun f(n)(if(< n 3)n(-(f(- n 2))(f(1- n)))))

Try it online!
1-indexed, plain recursive solution.

R, 38 bytes
f=function(n)`if`(n<3,n,f(n-2)-f(n-1))

1-indexed solution
Explanation :
The 'if' function has the same syntax as ifelse : ifelse(test, TRUE, FALSE).
In this solution, we create a function f that begins to test if the input n is strictly inferior to 3 (i.e. equals to 1 or 2 ; test part of the 'if'). If its the case, the output is simply the input (TRUE part).
The function otherwise recursively calls itself and outputs the final result (FALSE part)

Can we have a TIO link?

Mini-Flak, 72 bytes
(1-indexed)
({}(()()())(())[()()()()]){({}(([{}]({})))[({}([{}]{})[({})])][()])}{}{}
Try it online!
The TIO links have more comments, so it is easier to understand.

><>, 17+3 = 20 bytes
43\n;
?!\:@-{1-:}

Try it online!
Input is expected on the stack at the start of the program, so +3 bytes for the -v flag.

Fortress 0.1 Alpha, 39 bytes.
f(n)=if n<3then n else f(n-2)-f(n-1)end

The interpreter is archived here (direct download).
This language is old and dead, very dead. (1-indexed: f(1)=1, f(2)=2).
Can be placed into a program like this:
export Executable
f(n)=if n<3then n else f(n-2)-f(n-1)end
run(args) = do
    println(f(3))
end

Does this really need explaining? This is just the definition.

Is there absolutely no way of trying it online?

Nope. If there was, I would've found it by now. Follow the link, it's archived.

Julia, 24 bytes
f(n)=n>2?f(n-2)-f(n-1):n

1-indexed
Try it online!

Welcome to PPCG!

Charcoal, 34 33 bytes
Ａ¹αＡ²βＦ…²θ¿﹪ι²Ａ⁻βαβＡ⁻αβα⎇﹪Ｉθ²ＩαＩβ

Try it online!
1-indexed. I insist on writing answers in a language with a totally different purpose... Link to the verbose version.

Save 1 byte by casting the result of the ternary instead of the two variables.

x86-64 Machine Code, 29 bytes
Simple recursive solution; 1-indexed
The following is a function written according to the System V AMD64 calling convention that computes and returns the nth number of the Fibtraction sequence. The sole parameter, n, is passed in the EDI register. The function returns its result in the EAX register.
53
51
89 F9
83 EF 02
7E 10
E8 00 00 00 00
8D 79 FF
91
E8 00 00 00 00
29 C1
91
59
5B
C3

Try it online! (Hey, I finally figured out how to make TIO work for assembly language! Ignore the ugly boilerplate to print numbers… :-p)
Ungolfed assembly mnemonics:
Fibtraction:
   push     rbx           ; preserve original value in EBX
   push     rcx           ; preserve original value in ECX
   mov      ecx, edi      ; preserve original 'n' in ECX
   sub      edi, 2        ; EDI = n - 2
   jle      .Finished     ; if n <= 2, we're done (base case for recursion)
   call     Fibtraction   ; compute f(EDI), which is f(n - 2)
   lea      edi, [rcx-1]  ; EDI = n - 1
   xchg     eax, ecx      ; save result of f(n-2) in ECX (which we can now safely clobber)
   call     Fibtraction   ; compute f(EDI), which is f(n - 1)
   sub      ecx, eax      ; calculate f(n - 2) - f(n - 1)
.Finished:                ; fall through...
   xchg     eax, ecx      ; move result from ECX into EAX
   pop      rcx           ; restore original value to ECX
   pop      rbx           ; restore original value to EBX
   ret                    ; return, with result in EAX

Okay, it's assembly language, so there are no fancy built-ins to help us. But just look at all of those 1-byte opcodes! PUSH, POP, and XCHG are all very handy here.
These XCHG instructions are really just substitutions for register-to-register MOVes. We don't actually need to exchange the values; we just care about a one-way movement. But, although normally MOV reg, reg and XCHG reg, reg are both 2 bytes, there is a special 1-byte encoding for XCHG when one of the operands is the accumulator (EAX). Thus, this substitution saves us a few bytes (at the possible expense of speed).
The only long, ugly instructions are the CALLs, used to invoke the function recursively. (Technically, all of those 0s in the opcodes get replaced by the linker with the function's actual 32-bit relative displacement when the code gets linked, but the resulting binary will be the same size in bytes because this won't change the length of the instruction.) But there isn't really anything we can do to reduce the size. CALL can be emulated as PUSH+JMP, but just the PUSH instruction alone consumes more bytes than CALL!
The recursive nature of this algorithm made it a fun and interesting challenge—to me, at least. It's not very often in the real world that you get to write recursive code! It just isn't an efficient way to do things. (Double recursion leads to exponential complexity! Bleh!) Compilers also do a bad job, in general, optimizing it, so this hand-written assembly is head-and-shoulders above what a C compiler would generate for the naive solution:
int Fibtraction(int n)  { return n <= 2 ? n : f(n-2) - f(n-1); }

(although it has been optimized for size, rather than speed, obviously).

Ruby, 26 bytes
Nothing fancy here, it's just a translation of Python or Javascript solutions :
f=->n{n<3?n:f[n-2]-f[n-1]}

The results are 1-indexed.
Try it online!

SWI Prolog, 88bytes
Did I hear recursion? Prolog is here!
g(1,1).
g(2,2).
g(X,Y):-A is X-2,g(A,B),C is X-1,g(C,D),Y is B-D.
f(X):-g(X,Y),print(Y).

Try it:
SWISH

Can we have a TIO link?

Here you are: https://swish.swi-prolog.org/p/Fibtraction%20-%20Fibonacci%20but%20with%20subtraction.pl

Mathematica, 37 bytes
LinearRecurrence[{-1,1},{1,2},{#+1}]&

Does it work on Mathics? If so, can we have a TIO link?

Once again, the obvious answer is shorter

Although MartinEnder came up with an even shorter, more obvious solution.

Go, 50 bytes
func f(n int)int{if n>2{n=f(n-2)-f(n-1)};return n}

Try it online!

Braingolf, 22 bytes
[vl1-?!-|l1e2|l0e1|R]v

Try it online!
Why is it so long D:

VBA, 62 Bytes
Recursive function that takes input, n, as integer and outputs the 1-indexed  element of A061084
Function f(n):If n<3Then f=n Else f=f(n-2)-f(n-1):End Function

Positron, 63 bytes
a=function{k=$1;if(k>2)then{k=((a@(k-2))-(a@(k-1)))};return k;}

Try it online!

*aggressive parenthesizing*

@totallyhuman It's to get around the 5000000000 bugs lol

dc, 32 bytes
?3sb1sc[lblcdsb-sc1-d0<d]dsdxlbp

1-indexed.
Try it online!
Explanation
?     # Take input and push it onto the main stack.
3sb   # Push 3 into register "b".
1sc   # Push 1 into register "c".
[     # Begin macro definition.
 lblc # Load the values in registers "b" and "c" onto the main stack.
 dsb  # Duplicate the top-of-stack value and push it into register "b".
 -sc  # Push the difference of the top two values into register "c".
 1-d  # Subtract 1 from the top-of-stack value and duplicate the result.
 0<d  # If the result is greater than 0, execute the macro in register "d".
]     # End macro definition.
dsdx  # Duplicate the macro, push a copy into register "d", and execute the
      # remaining copy.
lbp   # Output the value stored in register "b".

Kotlin, 52 bytes
fun f(n:Int):Int{return if(n<3)n else f(n-2)-f(n-1)}

Try it online!

Groovy, 27 26 bytes
f={n->n<3?n:f(n-2)-f(n-1)}

Try it online!
Okay, so I feel like I stumbled upon a great language for golfing. This code is basically what most other answers are doing, if n is lesser than 3, then return n or else return f(n - 2) - f(n - 1). But there are a few cool things about this.
For a language that compiles to the JVM, Groovy is surprisingly terse. Variable declarations need no type definition. Functions (called closures in Groovy) are denoted with the {} syntax. it can be used to refer to the sole argument to the function, which means you don't need to specify the argument name and type. Turns out naming the argument was shorter. Combined with the ternary operator, this code ended up quite golfy for a "practical" language.

Tip: Using it is better if there are 3 or fewer references to it.

Pyth, 15 bytes
First time doing Pyth. ^^
L?<b3b-y-b2y-b1

Try it online!
Explanation
L?<b3b-y-b2y-b1

L                define a function y that takes an argument b
 ?<b3            if b < 3...
     b           ...return b
      -y-b2y-b1  else return y(b - 2) - y(b - 1)

12 bytes