text:
When is Thanksgiving?
Background
Some holidays have fixed, easy-to-remember dates, like Oct 31, Dec 25, etc. Some, however, want to be troublesome. They're specified as things like "the first Monday in September" or "the fourth Thursday in November". How am I supposed to know when that is?
All I know is that Thanksgiving is fast approaching, so I need a program to help me figure out when it is. Some people even say that it's tomorrow, so your program needs to be as short as possible to make sure I can re-type it in time.
The Challenge
Create a program or function that, given an up-to-four-digit year (e.g. 2015 or 1984), outputs or returns the date of the United States' Thanksgiving in that year. Thanksgiving is defined as the fourth Thursday of November according to the Wikipedia page. (Hint: that page also includes some interesting information on the date pattern.)
Input: a decimal number with a maximum of four digits representing a year in the Common Era (C.E.). Examples: 987, 1984, 2101
Output: the date, including month and day, on which Thanksgiving falls, or would fall if it existed, in that year. This may be in any reasonable format; use your best judgment. Use the Gregorian Calendar in all cases, even if it was not in use at the time.
(Note: Make sure to handle leap years correctly!)
Test cases
Input 1:
2015

Output 1:
Nov 26

Input 2:
1917

Output 2:
Nov 22

Scoring
Submissions will be scored in bytes. I recommend this website to keep track of your byte count, though you can use any counter you like.
Bonuses
-25% to your score if you handle B.C.E. dates as negative numbers (e.g. -480 would be the year of the battle of Thermopylae).
Negative test case input:
-480

Corresponding output:
Nov 25

This is code-golf, so the lowest score wins!
Edit: I am marking Thomas Kwa's TI-BASIC submission  as accepted. Don't let this discourage you from submitting new entries!
Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=64785,OVERRIDE_USER=45162;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

For anyone who is wondering when Thanksgiving will be coming up this year: Thanksgiving will be tomorrow .

But I had thanksgiving on October 10th? I'm sorry to say your question is late.

@JimmyJazzx brings up a good point. In Canada, Thanksgiving is on the second Monday in October. You should probably specify that you are talking about United States' Thanksgiving.

Must we use that byte counter or may we use that byte counter or may we use our own? Some languages like APL, have their own character set, which counts bytes differently

@Downgoat Use whichever byte counter you want. That's just the one I use personally and would recommend.

Do you want the de facto Thanksgiving dates or the dates that follow your rule?   Since 1789 (in the US), Thanksgiving Day was observed on inconsistent days.  From 1863 to 1940 it was on the last Thursday of November.  Since then it has been celebrated on the 4th Thursday of that month. https://www.archives.gov/legislative/features/thanksgiving/

@DavidCarraher The legal holiday is on the fourth Thursday.

@LegionMammal978, only since 1941 has Thanksgiving been taken to be on the 4th Thursday, even though it was officially celebrated before then.

"Some holidays have fixed, easy-to-remember dates, like Oct 31, Dec 25"   Those examples are easy to remember because they're really the same day:  octal 31 == decimal 25. ;-)

@Adrian McCarthy That wasn't unintentional.

What should be the output for 0?

@Eth I've got Nov 22 with my program, probably posting it soon.

@nicael I get that for 0 and 1.

@AdrianMcCarthy Whenever I forget when Christmas is, I always use this method of converting octal 31 to decimal :)

For an answer that does the bonus, should there be a year 0 between -1 and 1 or not?

What about Easter?

Most answers using buildin date functions apply the Julian calendar before 1582 and implement the date jump from Oct 4 to Oct 15 in 1582. The challenge states that we should "use the Gregorian calendar in all cases, even if it was not in use at the time.", so for example 1400 isn't a leap year. Also, the gap of 10 days in 1582 (or 11 days in 1752, which is more accurate for America) makes 1582 and 1752 good test cases. I'd say the correct answer for 1752 is Nov 23. 1582 would be Nov 25 and 1400 is Nov 27.

Is outputting the day of the year (e.g. 329 for Nov 26 in a common year) acceptable?

@Mego No, you need the month and day.

Are we allowed to output in the format MMDD (e.g. 1126 for Nov. 26)?

@ThomasKwa Sure, you can do MMDD.

TI-BASIC, 15 bytes * 0.75 = 11.25
Tested on my TI-84+ calculator
1129-dayOfWk(Ans+ᴇ4,9,1

Thankgiving is November 29, minus the day of the week of September 1st, where 1 is Sunday and 7 is Saturday. This outputs in the format MMDD.
Test cases: 2015 -> 1126, 1917 -> 1122, -480 -> 1125 have been verified. TI-BASIC seems to use the Gregorian calendar for all dates.
TI-BASIC doesn't support negative years, but this gets the bonus because we add 10000 to the input. Because the Gregorian calendar has a period of 400 years, this doesn't change the day of the week.

Holy crap. xD I never would've thought this would have worked like this, +1.

Good idea to add 10000. Nice.

I count 23 Letters. How can this be 15 Bytes ?

@StephanSchinkel TI-BASIC uses tokens that are stored in the calculators memory, I believe all the characters here are 1 byte except for the tokens dayofWK( and Ans which are 2 and 1 bytes each.

You tested it on a calculator? wow.

PHP, 65 48 42 41 36 (+2 for -F) = 38 bytes
<?date(Md,strtotime("4thuXI$argn"));

Takes input as the first command line argument. Runs with warnings, which are acceptable by our rules. Prints NovDD, where DD is the day of Thanksgiving.
No online link because ideone doesn't support command line args and I don't know of an online interpreter that does.
Thanks to Alexander O'Mara for teaching me a new trick, and primo for a significant reduction

This is funnier than Mathematica.

You can shorten the string to "fourth thu ofXI"

@Tryth Even shorter: "4thuXI". You can even drop the space between the year "4thuXI2015".

Using the command line option -F, input could be shortened to "4thuXI$argn".

Wait, this actually works? That's...that's just...I don't even...

Input could also be piped in directly, e.g. echo 2015 | php -F thanks.php.

Works for me. While I'm at it, Md needs no quotes, with E_NOTICE disabled.

Mathematica, 59 38 bytes
DayRange[{#,11},{#,12},Thursday][[4]]&

+1 Clever. There is also WolframAlpha["Thanksgiving " <> #] & where the date is entered as a string.

WolframAlpha returns the US Thanksgiving day dates from 1863 (when Lincoln declared it to be on the LAST Thursday of November) onward.  The US has observed Thanksgiving since 1789.

@DavidCarraher However, the OP states that the program has to work for at least 0 - 9999 C.E.

JavaScript (ES6), 42 40 31 bytes - 25% = 23.25
a=>28.11-new Date(a,8).getDay()

Since the date "may be in any reasonable format", this function uses DD.MM. I wrote a TeaScript answer with a different technique, but this formula was shorter.
Explanation
As the months are zero based, new Date(a,10) returns a Date object representing November 1 of the specified year.
Since getDay() returns a number representing the day of week from 0..6 we want to map from
Su Mo Tu We Th Fr Sa
0  1  2  3  4  5  6
to to to to to to to
4  3  2  1  0  6  5

then add 22. It turns out that (11 - new Date(a,10).getDay()) % 7 will do the trick. As @Thomas Kwa pointed out, this is the same as 28-new Date(a,8).getDay() which is 28 minus the day of the week of September 1.

Nice solution, I love how short it is and that it's still more understandable than most of entries.

Japt, 43 37 36 35 29 bytes - 25% = 21.75
Japt is a shortened version of JavaScript.
`{28.11-?w D?e(U,8).getDay()}

Hahaha, I found a really cheaty trick: the interpreter ignores any brackets inside strings (used to insert code) while decompressing them, so we can compress the entire source code to save a byte >:D
The two ?s should be the Unicode unprintables U+0098 and U+0085, respectively. Try it online!
After decompression, the code evaluates to this:
"{28.11-new Date(U,8).getDay()}"

Which evaluates to:
""+(28.11-new Date(U,8).getDay())+""

Which gives the proper output.
Uses intrepidcoder's technique, outputting in format dd.mm. Properly supports negative years.
Suggestions welcome!
Edit: As of Dec 2, you can now use this 11-byte code (scoring 8.25 points):
28.11-ÐU8 e

(I so wish I had implemented this sooner!)

Very nicely done.

This is now longer than vanilla JavaScript. Thomas Kwa has a much shorter formula.

@intrepidcoder Thanks, fixed.

Vitsy, 44 bytes
I'm calculating with pure mathemagics!
Golfed:
Ve2*V2-V41m+Vaa*Dv1m-Vv4*1m+7M-baa*/+N
/D1M-
Ungolfed (moved the method call to the first line to make it readable):
Ve2*V2-V4/D1M-+Vaa*Dv/D1M--Vv4*/D1M-+7M-baa*/+N

V         Save the input as a final variable.
 e2*      Push 28 to the stack.
    V         Push the input to the stack.
     2-         Subtract two.
       V4/D1M-        Get floor(input/4).
              +        Add it to the total.
               Vaa*Dv/D1M-          Get floor(input/100), and save 100 as a temp
                                    variable in the process.
                          -          Subtract it from the total.
                           Vv4*/D1M-         Get floor(input/400).
                                    +         Add it to the total.
                                     7M       Modulo by seven.
                                       -       Subtract the result from 28.
                                        baa*/+      Add .11
                                              N      Output as number.
There's probably a better algorithm for this (and this is likely horridly golfed), but for those wondering, my algorithm comes from here.
Try it online!
Do I get bonus points for calculating it and having exactly 42 bytes? Dreams ruined.
Thanks to @Hosch250 for pointing out I was doing it wrong. :D Fixed.

No. but you get a +1 from me ;)

It says that Thanksgiving in 2016 is Nov 28.  It is really Nov 24.

@Hosch250 You're right - fixed now.

JavaScript (ES6), 43.5
Actual byte count is 58. The bonus of -25% applies => 58 * 0.75 = 43.5
s=>new Date(s,10,(a=new Date(s,10).getDay())<5?26-a:a+21)

Pretty straight and silly way as it could be, without any tricky workarounds or calculations.
De-golf (ES5) + demo:

function t(s) {
    a = new Date(s, 10).getDay();
    alert(new Date(s,10,a<=4?26-a:a+21))
}

t(prompt())

Note, that entering year 0-100 produces 1900-2000 year. Though, it looks like 0-100 years give the same date as do 1900-2000, judging from the other answers.

Replacing a+18 with 22, because it's called only in "else", and "else" occurs only if a is neither greater nor less than 4, i.e. exactly 4.

Replacing a<4?26-a:a>4?a+21:22 with a<=4?26-a:a+21

Pardon me if I'm wrong, but isn't a<4?x:a>4?y:a+18 equivalent to a<4?x:a>4?y:22?

BTW, it tells me the wrong year for any input from 0 to 99. Not sure if this matters, though.

@Eth LOL of course you're right, didn't think that's always 4+18 :D

@Eth hm, 0 to 99 is indeed wrong, let my try fixing that.

@Eth It looks like 0-100 give the same date that 1900-2000, judging from the other answers.

One more byte: x<=4 == x<5 ;)

Also, you don't need to alert; returning is enough. This means you can cut off another sizable chunk: s=>new Date(s,10,(a=new Date(s,10).getDay())<5?26-a:a+21)

@Eth That's just insane -  so obvious, but I couldn't golf this anymore... :D

can you drop the new keyword?

@roy No, won't work.

Python, 38 * 0.75 = 28.5 bytes
lambda x:28.11-(x-2+x/4-x/100+x/400)%7

This works with negative years in the manner specified in the question, although it's come to my attention that there is no year 0 in the Gregorian calendar so this behavior is a bit suspect.

You can drop f=.

How does this work for negative dates? Does modulo in Python apply to negatives? :O

It should be shorter to use string reps, "Nov "+`...`

@VoteToClose Python modulo gives an answer with the same sign as the second argument. Thus -40%7==2 but -40%-7==-5

@quintopia Wait, hold on, I'm an idiot. Okay. That makes sense.

I think you can change "Nov "+ at the beginning to +"-11" at the end to save a byte.

user5535756 would like to know how this works (but doesn't have enough rep to comment).

This appears to be using the Doomsday Rule for calculation - is that correct?

It uses Sakamoto's algorithm.

You could save a few bytes by outputting in dd.mm format: lambda x:28.11-(x-2+...

Yes, this is just a very specific case of Sakamoto's algorithm. @ETHproductions thanks for the further golfing tip! Didn't think this could get any shorter.

TeaScript, 35 33 24 bytes - 25% = 18
28.11-new D(x,8).getDay¡

This is the same method as my JavaScript answer, which uses Thomas Kwa's clever formula.
Alternate Version with Explanation
r(22,28)F(#/h/t(new D(x,10,l)))+'-11'

r(22,28)    // Range from 22 to 28
        F(    // filter, keeps elements for which the function returns true.
          #    // Expands to function(l,i,a,b)
           /h/    // RegExp literal, Thursday is the only day with an 'h'.
              t(    // test, true if date string contains an 'h'.
                new D(x,10,l) // Create date object
                             ))+'-11' // Append '-11' for the month.

It's 35 chars, but 36 bytes due to ¡ :)

@nicael Not by this site, it's not ;)

Hm, getting 36 with https://mothereff.in/byte-counter#%2811-new%20D%28x%2C10%29.getDay¡%29%257%2B22%2B%27-11%27.

@Downgoat usually uses this format, in which all chars up to U+00FF are 1 byte.

Python, 83 81 78 bytes
from datetime import*
lambda a:'Nov '+`((10-datetime(a,11,1).weekday())%7)+22`

-2 bytes: added a name to import (thanks @Κριτικσι Λίθος)
-1 bytes: changed to *import** (thanks @FryAmTheEggman)
-2 bytes: changed to repr to convert the day (thanks @willem)

Just a suggestion to reduce byte count: use import datetime as d and then you can use d for every time you use datetime in your program.

You could also try pandas. import pandas;print'Nov '+\((10-pandas.datetime(input(),11,1).weekday())%7)+22``

@ΚριτικσιΛίθος but then datetime.datetime would only be d.datetime, wouldn't it?

from datetime import* is even a bit shorter, as you won't need the d. any more

Excel, 367 154 53 - 25% = 39.75 bytes
Assumes the year is held in cell A1, in Date format.  Returns the integer number of the day in November on which Thanksgiving is held.
This only accounts for normal leap years.  It does not account for the fact that the years, 2100, 2200, 2300 are not leap years.
This is only designed to work for 1621 onwards - i.e. since Thanksgiving began being held.  (Although it will certainly work all the way back to 0 A.D.).
=IF(MOD(YEAR(A1),4)=0,IF(WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,1127-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),1134-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))),IF(WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,1127-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),1134-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))))

Pretty-printed:
=IF(MOD(YEAR(A1),4)=0,
    IF(WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,
       1127-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),
       1134-WEEKDAY(305+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))),
    IF(WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))<6,
       1127-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy")))),
       1134-WEEKDAY(304+DATEVALUE(("01/01/"&TEXT(A1,"yyyy"))))))

Gah!  Instead of calculating based on the 1st of Jan, then doing lots of leap year calculations to cope with the 29th of Feb, I should have based the calculations on the 1st of Nov.  n.b. This now deals correctly with the years 2100, 2200 and 2300, but makes the implementation dependent on your Excel installation's default date format. This version is designed for dd/mm/yyyy:
 =IF(WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy"))))<6,
     1127-WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy")))),
     1134-WEEKDAY(DATEVALUE(("01/11/"&TEXT(C1,"yyyy")))))

And now that I've done the pfaffing about to get a terse calculation in Smalltalk, backporting it to Excel results in:
=DATE(A1,11,MOD(12-WEEKDAY(DATE(9600+A1,11,1)),7)+22)

(with the year still in A1, but as an integer). This works even for years 2100, 2200 and 2300, for all dates from 7700BC/E onwards, using Thomas Kwa's date repetition trick.

When I try this with dates prior to 1900 it doesn't work in my copy of excel.

The long version doesn't work as well.

For old dates, use Excel User's pre-1900 dates workbook.  http://exceluser.com/downloads/examples/post_900_123/index.html

Questions about whether this works aside, I don't think you're allowed to output just the date in November; you need a "Nov" or "11" in some form.

@Thomas Kwa The date input is the year, in date format.  The calculation then works out the day of the week that the 1st of November falls on, then calculates what date the fourth Thursday in November is.

Yes, the spec allows for numeric Novs. I'll amend to suit

Jython, 141 155 Bytes
Uses the Java Calendar and Scanner classes with Python syntax.
import java.util.Scanner as s;import java.util.Calendar as c
d=c.getInstance();k=s(System.in);d.set(c.YEAR,k.nextInt());d.set(c.DAY_OF_WEEK,c.THURSDAY)

Edit: Minor syntax issues, added 14 bytes.
Also see my Brainfuck version.

PowerShell, 67 64 84 72 58 45 Bytes
param($a)'Nov';28-(date "00$a/9/1").DayOfWeek

We take our input integer as $a, and immediately output Nov and a newline. Then we take $a and prepend it with zeroes and September 1st with 00$a/9/1 before generating a new date and determining what DayOfWeek that is. If September 1st is on a Sunday (.DayOfWeek equal to 0), Thanksgiving is on the 28th. If September 1st is on a Monday (.DayOfWeek equal to 1), Thanksgiving is on the 27th. And so on. Thus, we subtract that day of the week from 28 to output our answer.
Prepending with double-zeroes accounts for single- and double-digit years without interrupting parsing for three- or four-digit years. Doesn't work for negative numbers, as .NET datetime doesn't support years less than 0.
Thanks to TessellatingHeckler and Toby Speight for assistance on this.

"{0:D3}/Nov/$_" -f $a is shorter than "$($a.ToString("000"))/Nov/$_" and produces the same result, and I think you could use 11 instead of Nov

@n0rd Ah, excellent! Yes -- the Nov was a remnant from when I was trying to get it to recognize two-digit years properly, so I'll swap that out, too. Thanks!

@TessellatingHeckler That approach works, but you need to prepend two zeroes to account for one-digit years, else you're back into the 20XX that I ran into. Thanks for the assist - I updated the answer.

@TessellatingHeckler On my system, at least, inputting single-digit years into date "11/1/$a" results in Thursday, November 1, 2007 12:00:00 AM. This is because we're not editing the Calendar.TwoDigitYearMax property, so when it parses, we're stuck with double-zero-padding to get around that.

Right, right. Double padding it is.

I think you can shorten this a little further by picking a different sample date for day-of-week.  See my answer where I use a date in early May.  And then you could use 28-... or 29-... depending on whether PowerShell reports 0-based or 1-based weekdays.

Thanks @TobySpeight - That golfed a bunch! I selected September 1st because that lined up the dates nicely that I could just subtract them.

Golfscript, 25 * 0.75 = 18.75 bytes
~.4/.25/.4/2---+7%28\--11

This uses Sakamoto's formula for the day of the week. Since there are people doing this, the output is in the form of dd-mm. My previous submission can be found below:
~.4/.25/.4/2---+7%"Nov "28@-

Pyth, 30 28 * 75% = 21 bytes
I'm 100% positive that this could be made shorter, but hey, it's my first Pyth program! \o/
-28.11%+-+-Q2/Q4/Q100/Q400 7

Test suite
Outputs the date in dd.mm format.
Please suggest ways to golf this if you can! I'd like to learn more about Pyth.

TSQL, 478 296 bytes
Just for funsies. Typically, you'd have a date dimensional table to make this a simple select * from dimDate where [Year] = @Year and [Holiday] = 'Thanksgiving' but in the absence of that...
create function a(@y varchar(4))returns date as begin declare @d date,@i int=0 set @d=convert(date,@y+'-11-01')declare @t table(d date,c int identity)while @i<28 begin if datepart(weekday,@d)=5 insert @t(d) select @d select @d=dateadd(d,1,@d),@i+=1 end select @d=d from @t where c=4 return @d end

Ungolfed:
if exists(select * from sys.objects where name='a' and [type]='FN') drop function a
go

create function a(@y varchar(4))returns date
-- select dbo.a('2015')
as
begin
    declare @d date,@i int=0;

    set @d=convert(date,@y+'-11-01'); -- cannot golf out dashes for dates <year 1000

    declare @t table(d date,c int identity)

    while @i<28
    begin -- populate "November" array
        if datepart(weekday,@d)=5 insert @t(d) select @d -- assumes @@datefirst = 7
        select @d=dateadd(d,1,@d),@i+=1
    end;

    select @d=d from @t where c=4

    return @d

end

Is this really the shortest way?

I suppose I may not be familiar with the rules of code golf, but the answer creates a DB object that accepts input and returns output to match the OP. There's some obvious shortening that could occur if input can be accepted into inline code but this was my thought for the function object type. I'm sure it could be golfed further in either case. @ThomasKwa, do you have suggestions?

Well, it seems to me you could use the pure-math formula that this answer mentions and not bother with all that date object stuff.

not strictly a pure-math solution, but reading that answer definitely gave me some ideas to golf out 200 characters. Thanks!!

(I meant (28 - ( x - 2 + floor(x / 4) - floor(x / 100) + floor(x / 400) ) % 7) Yeah, reading other answers tends to help a lot.

TBH, i don't fully understand why that formula works ( not pegged to a Datepart of Day = Thursday? ).

This is a shorter way for the first line: if object_id('a','FN') is not null drop function a

Got this down to 215 bytes using a mini-tally table and an ITVF - see my answer below

Now down to 186 bytes, handling negative years at least as far back as 5480 BCE.

@lirtosiast there is a shorter way now

Excel, 64 48
Year in A1
=DATE(A1,11,CHOOSE(WEEKDAY(DATE(A1,11,1)),26,25,24,23,22,28,27))
=DATE(A1,11,MOD(12-WEEKDAY(DATE(A1,11,1)),7)+22)

As Excel is localization based and I would like to test this. Please explain what the functions do, so I can select the proper one in my language.

Also, this doesn't work for dates prior to 1900 (at least in my copy of Excel)

Also, you saved 13 bytes on TEXT from =TEXT(DATE(A1,11,MOD(12-WEEKDAY(DATE(A1,11,1)),7)+22),"d mmm") - the output is an integer without formatting.

@user3819867, that's how excel stores its dates. formatting is left up to the user

@AngeloFuchs, DATE returns a date value, using year, month, day as parameters. MOD returns the remainder part of a division (modulus). WEEKDAY returns the day of week of a date (1=Sunday, 2=Monday, etc).

Befunge, 41 Bytes
47*&:::4"d"*/\"d"/-\4/++5+7%-" voN",,,,.@

Run on this interpreter.
Explanation:
A common year is 365 = 1 mod 7 days, so the year plus every 4th year, minus every 100th  (d in ascii) year, plus every 400th years accounts for any leap days (including the present year). The result of :::4"d"*/\"d"/-\4/++ can then be thought of as March 5th, the first day after February to fall on the same day as the first day of the year in common years. After that we calibrate to the pattern with 5+7%- subtracting a number of days of the week from the 28th(the 47*stored earlier) of November. Then print.
A version correcting for B.C. years is currently longer than the bonus provides for, at 59 -25% = 44.25 bytes:
47*&v
!`0:<+*"(F"_v#
" voN",,,,.@>:::4"d"*/\"d"/-\4/++5+7%-

Matlab, 78 bytes
x=find(all(bsxfun(@eq,datestr(datenum(input(''),11,1:30),'ddd'),'Thu')'));x(4)

Ruby, 60 58 42.75 39 * 0.75 = 29.25 bytes
->y{puts"Nov #{28-Time.new(y,9).wday}"}

42.75 bytes
->y{puts"Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"}

58 bytes
->y{puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"}

60 bytes
->y{puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11,1).wday]+21}"}

Ungolfed:
-> y {
  puts "Nov #{[5,4,3,2,1,7,6][Time.new(y,11).wday]+21}"
}

Tests:
->y{puts"Nov #{28-Time.new(y,9).wday}"}.(2015)
Nov 26

->y{puts"Nov #{28-Time.new(y,9).wday}"}.(1917)
Nov 22

->y{puts"Nov #{28-Time.new(y,9).wday}"}.(-480)
Nov 25

Or using the September 1st trick: "Nov #{28-Time.new(y,9).wday}" 30 bytes

@josh That's brilliant. Updating it :)

PHP 5.3+, 59 bytes
This uses PHP builtin function strtotime to parse the date.
<?=gmdate('M d',strtotime("Next Thursday $_GET[Y]-11-19"));

This expects the value to be passed over GET parameter Y OR over php-cli Y=<year>.
It tries to find the next thursday after 19th November.
So far, with the tests I've made, it works fine.
Be aware that 2-digit years may be interpreted differently.
I use gmdate to avoid timezone issues, but it works equally well using date (at least, where I live).

An answer is not an appropriate place to discuss the validity of an input method. I've created this option in the default I/O meta post (so the community can vote on it) and moved your conversation to chat. (CC @Mego)

GNU coreutils, 35 bytes
seq -f$1-11-2%g 2 8|date -f-|grep h

Simply searches the week 22-28 November for a Thursday.  Run it in a C or POSIX locale, as I depend on Thursday being the only day abbreviation to contain a 'h'.

Here's a cleverer answer, albeit a byte longer:
echo Nov $((28-`date -d$1-5-5 +%w`))

We retrieve the day-of-week number of a date in a fairly arbitrary week between March and September (so day and month are one digit each, and we're not affected by a possible leap day).  We pick the day so that it's a Sunday (%w==0) when Thanksgiving is on the 28th.  We can then subtract that value from 28 to obtain the appropriate Thursday.

This works unless Sean Connery runs it.

T-SQL 215 bytes 248 * 0.75 = 186 bytes
create function t(@y int)returns table return select x=convert(char(6),x,107)from(select x=cast(dateadd(dd,d,dateadd(yy,@y-2015+7600,'20151101'))as date)from(select d=21+n from(values(0),(1),(2),(3),(4),(5),(6))b(n))c)t where datepart(weekday,x)=5

Ungolfed
set nocount on;
if object_id('dbo.t') is not null drop function dbo.t
go

create function t(@y int)returns table return
    select x=convert(char(6),x,107)
    from (
        select
        x=cast(dateadd(dd,d,dateadd(yy,@y-2015+7600,'20151101'))as date)
        from (
            select d=21+n
            from (values (0),(1),(2),(3),(4),(5),(6))b(n)
        )c
    )t
    where datepart(weekday,x)=5
go

which with this test scaffold
select
  [ 2015 = Nov. 26]=(select x from dbo.t( 2015))
 ,[ 1917 = Nov. 22]=(select x from dbo.t( 1917))
 ,[ 1752 = Nov. 23]=(select x from dbo.t( 1752))
 ,[ 1582 = Nov. 25]=(select x from dbo.t( 1582))
 ,[ 1400 = Nov. 27]=(select x from dbo.t( 1400))
 ,[ -480 = Nov. 25]=(select x from dbo.t( -480))
 ,[-5480 = Nov. 28]=(select x from dbo.t(-5480))
;
go

yields as desired
2015 = Nov. 26  1917 = Nov. 22  1752 = Nov. 23  1582 = Nov. 25  1400 = Nov. 27  -480 = Nov. 25 -5480 = Nov. 28
--------------- --------------- --------------- --------------- --------------- --------------- ---------------
Nov 26          Nov 22          Nov 23          Nov 25          Nov 27          Nov 25          Nov 28

Smalltalk - Squeak and Pharo, 69 57 54 49 35 34 33 32 - 25% = 24 bytes
"Nov nn": 69B 49B (-25% = 36.75B)
11nn (anInt): 57 54 32B (-25% = 24B)
"Year supplied as an integer value, y
 Result provided as an integer value, 11nn
 Methods Date>>y:m:d: and >>w created as duplicates
 of year:month:day and weekdayIndex"
(12-(Date y:y m:11d:1)w)\\7+1122

Previous versions
11nn output
"Year supplied as an integer value, y
 Result provided as an integer value, 11nn"
(12-(Date year:y month:11 day:1) weekdayIndex)\\7+1122

"Year supplied as an integer value, y
 Result provided as an integer value, d, prefixed by 11"
d:=(12-(Date year:y month:11 day:1) weekdayIndex)\\7+1122

Nov nn output
"Year supplied as an integer value, y  Result provided as a string, 'Nov nn'"
'Nov ', (12-(Date year:y month:11 day:1) weekdayIndex\\7+22) asString

nn output
"Year supplied as an integer value, y  Result provided as an integer value, d"
d:=(12-(Date year:y month:11 day:1) weekdayIndex)\\7+22

n.b. This is provided as a program - specifically a Workspace expression - rather than as a method.
It assumes the input is a given (as per the phrasing "given an up-to-four-digit year".
Including the declaring and giving of the input would add another 11 characters:
|y|y:=2015.(12-(Date y:y m:11 d:1)w)\\7+1122
Thanks to eMBee, for showing how to remove yet one more char - the whitespace immediately before the 'w'.
Actually, that inspired me to try removing the whitespace before 'd:' :
|y|y:=2015.(12-(Date y:y m:11d:1)w)\\7+1122
Which worked!

As per the OP's clarification, the day number version is not valid.

I agree - but given there are quite a few day-number-only versions in the list, I put it there for an apples-to-apples comparison

Pike, 87 91 107 77 76 bytes - 25% = 57
string t(int y){return"Nov "+((11-Calendar.Day(y,11,1)->week_day())%7+22);}

leaving the old one in for comparison because i find it more clever in terms of taking advantage of the Calendar module, but the above is way shorter.
string t(int y){object n=Calendar.Month(y,11);return"Nov "+(n->weeks()->day(4)&n->days())[3]->month_day();}

This doesn't seem to take input.

yeah, i got confused by that, some solutions have a function definition and some just use a variable that is not defined anywhere, so i am not sure what i am supposed to use for the bytecount.

I think that the answers which you see as using "a variable that is not defined anywhere" are actually using a very short function declaration syntax. There are one or two answers which use esolangs which have special treatment for stdin and so favour writing full programs. I don't know Pike, but if you can remove whitespace and abbreviate the function name to get string t(int y){object n=Calendar.Month(y,11);return"Nov "+(n->weeks()->day(4)&n->days())[3]->month_day();} then I count that as 107 bytes.

i thought i had seen a few that weren't function declarations, but they appear to have been fixed, only the smalltalk example doesn't fit. if that is valid i could shave another 17 bytes of this one...

The Smalltalk version is written as a program - specifically a Workspace expression. We were told we are given an input, rather than soliciting input.

@euan-m: well, it also says we are supposed to create a program or function. in smalltalk i would make it a block: [:y|...] that defines y as the input variable and only adds 5 bytes; btw: you can remove one more space from ) w -> )w ...

@euan-m: you also need to re-add the 'Nov ', ... asString

It's a program - a short one. the Nov doesn't need re-added - it's now output as an integer  11nn.  The rules got explicitly amended to allow the winning entry.

oh,. that's why you add 1122, sorry, now i get it.

returning an integer is, uhm, interesting. no complaints, it fits the task. but if i wanted something actually practical i'd have gone for {11.(...)}, just slightly longer...

@eMBee I know nothing about Pike... but I'd think the space after the return is unnecessary.

good catch, indeed it works without. thanks!

VBA, 124 bytes * 75% = 93 bytes
Function e(y)
For i = 1 To 7
x = DateSerial(y, 11, 21) + i
If Weekday(x) = 5 Then e = Format(x, "mmm dd")
Next
End Function

I'm not sure if spaces count, it's somewhere between 102 and 124, feel free to edit.
If integers are a valid output I'm more than happy to remove the Format part.

Spaces count; if they're unnecessary to the program you can remove them though.

TSQL, 53 52 bytes
DECLARE @ CHAR(4)=2000

PRINT DATEADD(d,59,DATEDIFF(d,1,DATEADD(m,9,@))/7*7)

Fiddle
Calculating monday before or on september 2nd and adding 59 days
(better than calculating monday before or on october 4th and adding 31 days because october is the 10th month thus saving 1 byte)

Perl, 92 bytes
use Time::Local;(localtime(timelocal 0,0,0,$_,10,$ARGV[0]))[6]==4?print "Nov $_":0for 22..28

EDIT : Fixed output format, fixed bug e.g. 2012 result, used shorter "for" format.  Thanks to msh210.

This is shorter and does the same thing: use Time::Local;(localtime(timelocal 0,0,0,$_,10,$ARGV[0]))[6]==4?print:0for 22..29. But both scripts suffer from the same flaws: (1) they don't print a representation of the month as required; (2) they have the wrong output for e.g. 2012.

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

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


text:
Black Friday Queue Managment
Introduction
You are the manager of the electronics department in a major retail store and the biggest sales day of the year is this Friday. To help manage the crowds, your store is implementing a ticket system for the biggest deals, where customers must present a ticket before purchasing an item. Your job is to write a program to validate the tickets.
Since the only available computer in the store (due to budget cuts) is a dinosaur with a broken keyboard, (and all you have is USB keyboards, which aren't compatible) you'll have to input your program with a mouse. Therefore, your program should be as short as possible.
Products
You store is running sales on the five different products listed below. Each product has an all lowercase name and different rules on how many can be purchased and at what time of day.

television: There are 5 flat-screen televisions in stock that may be purchased from 00:00:00 (midnight) to 00:59:59.
smartphone: There are 10 smartphones in stock, but any customer in line from 00:00:00 (midnight) to 00:59:59 receives a voucher for one once they run out.
tablet: There are 10 tablets that may be purchased at anytime.
laptop: There are an unlimited number of laptops that may be purchased from 00:00:00 (midnight) to 07:59:59.
lightbulb: There are an unlimited number of light bulbs that may be purchased at anytime.

Input
A multi-line string with each line in the following format. Lines are sorted by the time-stamp.
<time stamp> <product name> <ticket number>

The ticket number is 8 digits long. The last digit is a check-digit equal to the sum of the first seven digits modulo 10. To be valid, a ticket number must have the correct check-digit and must be strictly greater than all previous ticket numbers.
The product name is one of the string listed above.
The time stamp is the time of day in the format HH:MM:SS where HH is the two-digit hour from 00-23, and MM and SS are the two-digit minute and second respectively.

Output
The output is one of the following strings, with one line per ticket. The conditions must be applied in order.

Expired offer (Applies to televisions, smartphones, and laptops.) The time-stamp of the ticket is after the cutoff to buy the product.
Invalid ticket Either the ticket number is less than or equal to the number of the previous ticket, or the check-digit is invalid.
Give voucher (Applies to smartphones.) The product is out of stock, but all the customers in line before the offer expires get a rain check.
Out of stock (Applies to televisions and tablets.) All of the product has been sold. Sorry, quantity was limited.
Accepted All conditions are met, so give them the product. Note that only accepted tickets reduce the number of items in stock.

Example
Input                           Output
----------------------------    --------------
00:00:00 television 00010001    Accepted
00:00:25 smartphone 00011697    Accepted
00:01:25 laptop 00030238        Accepted
00:02:11 smartphone 00037291    Accepted
00:02:37 lightbulb 00073469     Invalid ticket
00:03:54 smartphone 00096319    Accepted
00:05:26 tablet 00152514        Accepted
00:06:21 tablet 00169893        Accepted
00:07:10 television 00190268    Accepted
00:07:47 smartphone 00194486    Accepted
00:07:55 tablet 00220071        Accepted
00:08:20 lightbulb 00321332     Accepted
00:10:01 smartphone 00409867    Accepted
00:11:10 tablet 00394210        Invalid ticket
00:11:46 television 00581060    Accepted
00:12:44 lightbulb 00606327     Accepted
00:13:16 tablet 00709253        Accepted
00:13:53 television 00801874    Accepted
00:14:47 laptop 00832058        Accepted
00:15:34 smartphone 00963682    Accepted
00:16:24 smartphone 01050275    Accepted
00:17:45 tablet 01117167        Accepted
00:18:05 laptop 01107548        Invalid ticket
00:19:00 lightbulb 01107605     Invalid ticket
00:19:47 lightbulb 01492983     Accepted
00:19:50 smartphone 01561609    Accepted
00:21:09 television 01567098    Accepted
00:21:42 laptop 01597046        Accepted
00:22:17 smartphone 01666313    Accepted
00:24:12 tablet 01924859        Accepted
00:24:12 smartphone 02151571    Accepted
00:25:38 smartphone 02428286    Give voucher
00:31:58 television 02435284    Out of stock
00:35:25 television 02435295    Out of stock
00:52:43 laptop 02657911        Invalid ticket
00:53:55 smartphone 02695990    Give voucher
01:08:19 tablet 02767103        Accepted
01:34:03 television 02834850    Expired offer
01:56:46 laptop 02896263        Accepted
02:02:41 smartphone 03028788    Expired offer
02:30:59 television 03142550    Expired offer
02:51:23 tablet 03428805        Accepted
03:14:57 smartphone 03602315    Expired offer
03:27:12 television 03739585    Expired offer
03:56:52 smartphone 03997615    Expired offer
04:07:52 tablet 04149301        Accepted
04:12:05 lightbulb 04300460     Invalid ticket
04:24:21 laptop 04389172        Accepted
04:40:23 lightbulb 04814175     Accepted
04:40:55 tablet 04817853        Accepted
04:42:18 smartphone 04927332    Expired offer
05:06:43 tablet 05079393        Out of stock
05:16:48 tablet 05513150        Out of stock
05:33:02 television 05760312    Expired offer
05:43:32 tablet 06037905        Out of stock
06:12:48 smartphone 06440172    Expired offer
06:35:25 laptop 06507277        Accepted
06:42:29 lightbulb 06586255     Invalid ticket
06:55:31 lightbulb 06905583     Accepted
06:55:33 lightbulb 06905583     Invalid ticket
07:40:05 smartphone 07428006    Expired offer
07:49:12 television 07588086    Expired offer
08:14:56 laptop 08111865        Expired offer

I have tried to make the example cover every possible output scenario, but please leave a comment if anything is unclear.
This is code-golf, you may write a program or function, and standard loop-holes are disallowed.

Javascript(ES6), 396 433 419 bytes
h=0;f=1/0;i={television:{c:5,s:0,e:1},smartphone:{c:10,s:0,e:1,v:1},tablet:{c:10,s:0,e:24},laptop:{c:f,s:0,e:8},lightbulb:{c:f,s:0,e:24}};while(1){t=prompt().split(' ');a=t[0];r=a[0]+a[1]-0;o=i[t[1]];m=0;z='Accepted';u=t[2]-0;u<=h||(u-u%10+'').split('').reduce((p,c)=>-(-p-c))%10!=u%10?m='Invalid ticket':0;r<o.s||r>=o.e?m='Expired offer':0;if(!m)o.c?o.c--:(o.v?z='Give voucher':m='Out of stock');!m?h=u:0;alert(m?m:z)}

Edit: Reduced size by using es6 big arrow function
More readable:
h=0
f=1/0
i={television:{c:5,s:0,e:1},smartphone:{c:10,s:0,e:1,v:1},tablet:{c:10,s:0,e:24},laptop:{c:f,s:0,e:8},lightbulb:{c:f,s:0,e:24}}
while(1){t=prompt().split(' ')
a=t[0]
r=a[0]+a[1]-0
o=i[t[1]]
m=0
z='Accepted'
u=t[2]
if(u<=h||(u-u%10+'').split('').reduce(function(p,c){return-(-p-c)})%10!=u%10)m='Invalid ticket'
if(r<o.s||r>=o.e)m='Expired offer'
if(!m){if(o.c)o.c--
else o.v?z='Give voucher':m='Out of stock'}if(!m)h=u
alert(m?m:z)}

Interestingly the longer code is faster: http://jsperf.com/compare-read
GUI with same logic:

var app = angular.module('app', []);

app.controller('MainCtrl', function MainCtrl ($scope) {
  $scope.items = {
    television: {c: 5, s:0, e: 1},
    smartphone: {c: 10, s:0, e: 1},
    tablet: {c:10, s:0, e: 24},
    laptop: {c:Infinity, s: 0, e: 8},
    lightbulb: {c: Infinity, s: 0, e: 24},
  };

  var h = -1;//highest

  $scope.hours_offset = 0;

  $scope.ticket = {};
  for (var i = 0; i < 8; i++) $scope.ticket[i] = 0;

  $scope.selected_item = -1;

  $scope.nums = new Array(10);

  $scope.history = [];

  $scope.buy = function() {

  }
  $scope.selectItem = function($i) {
    $scope.selected_item = $i;
  }

  $scope.purchase = function() {
    if ($scope.selected_item === -1)
      return;

    var ticnum = '';
    var msg = 'Accepted';

    for(var key in $scope.ticket)
      ticnum+=$scope.ticket[key];

    var d = new Date();

    //Variable declarations to setup for code like the code I designed for console
    r = d.getHours()-$scope.hours_offset;//hour
    o = $scope.items[$scope.selected_item];//item
    m = 0//msg
    z = 'Accepted'//default_msg
    u=ticnum

    //This is copied from my console code
    if(ticnum<=h||(ticnum-ticnum%10+'').split('').reduce(function(p,c){return-(-p-c)})%10!=ticnum%10)m='Invalid ticket'
 if(r<o.s||r>=o.e)m='Expired offer'
 if(!m){if(o.c)o.c--
 else o.v?z='Give voucher':m='Out of stock'}if(!m)h=ticnum

    msg = m?m:z;

    $scope.history.unshift({
      time: time(d),
      item: $scope.selected_item,
      ticket_num: ticnum,
      message: msg
    });

  }
});

function time(date) {
  return padToTwo(date.getHours()) + ':' + padToTwo(date.getMinutes()) + ':' + padToTwo(date.getSeconds());
}

function padToTwo(number) {
  return number = ("00"+number).slice(-2);
}
#parent {
  width: 100vw;
  height: 100vh;

  padding-bottom: 25vh;
}
#parent > div {
  padding-top: 25vh;

  -webkit-display: flex;
  display: flex;

  -webkit-flex-direction: row;
  flex-direction: row;

  -webkit-align-items: flex-start;
  align-items: flex-start;
  -webkit-justify-content: center;
  justify-content: center;
}

#items {
  width: 15vw;
  min-width: 110px;
  margin-right: 4vw;
  background-color: #222223;
  color: #eeeeef;
  border-radius: 4px;
  border: 2px solid black;
}

#items > span {
  box-sizing: border-box;
  display: block;
  padding: 5px;

  -webkit-transition: .2s background-color ease-in-out;
  transition: .2s background-color ease-in-out;

  text-align: center;

  width: 100%;

  border-radius: 4px;
}
#items > span:hover, #ticket p:hover {
  background-color: gray;
}
#items > span.selected, #ticket p.selected {
  background-color: #999999;
}
#ticket {
  -webkit-display: flex;
  display: flex;

  -webkit-flex-direction: row;
  flex-direction: row;

  margin-right: 4vw;

  color: #eeeeef;
}

#ticket p {
  margin: 1px;
  padding: 3px;
  width: 20px;
  text-align: center;
  background-color: #22222f;
  border: 2px solid black;
  border-radius: 3px;
}

#purchase {
  padding: 15px;
  padding-top: 6px;
  padding-bottom: 6px;

  background-color: #22222f;
  border: 2px solid black;
  border-radius: 3px;
  color: #eeeeef;
}
#purchase:active {
  background-color: gray;
}

#error {
  margin-top: 15px;
  color: red;
}

  For testing hours-offset (If it's 6:00 setting this to 18 would simulate it being midnight): <input ng-model="hours_offset" type="number"></input>

      {{::name}}

{{::$index}}

    Purchase

{{error_msg}}

      {{value}}

Welcome to PPCG. While your GUI is something, the object of code golf is to write the shortest program possible. Since you're using JavaScript, you could take the input string as function parameter and return the output. You should also remove unnecessary whitespace and shorten variable names. Why don't you look at some other questions to get an idea for how the site works?

@intrepidcoder Of course you would minify the code afterwards!  But based on the scenario it would seem to me console would be ineffective without a keyboard!

Per the rules outlined in our help center, this post is off topic in its current state. All solutions to challenges should: [...] Be a serious contender for the winning criteria in use. For example, an entry to a code golf contest needs to be golfed[.]

That was an absurd rational for short code length and had nothing to do with the actual problem. The combined size of your three programs is 4.51 KB. If you don't try to make it smaller, you post will probably be deleted.

@intrepidcoder Oh yes!  I forgot about that, there were a lot of constraints xD.  When you say last digit you do you mean the MSB or the LSB?  I'm guessing the LSB but I wish to be sure.

I mean the least-significant digit. E.g. for the 1st invalid example 00073469 is 0+0+0+7+3+4+6 = 20 % 10 = 0 != 9

@intrepidcoder Great, thanks!  See my latest edit.

Congratulations, this now passes all test cases. +1 I can also give some tips to make this smaller if you'd like.

@intrepidcoder Sure, how can it be shrunk?

@intrepidcoder Thanks for the edit, it is cleaner now.  I believe you typo'd the byte count, I changed it back to 433 (and double checked that was correct using 2 byte counters).

Usually those are more important. But this is code-golf. :) To start you can use an arrow function, for instead of a while loop, | instead of || (some places). Look at this post for more tips.

Sorry for accidentally changing the byte count.

source: Stack Exchange

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

sort: votes


text:
Count sums of two squares
Given a non-negative number n, output the number of ways to express n as the sum of two squares of integers n == a^2 + b^2 (OEIS A004018). Note that a and b can be positive, negative, or zero, and their order matters. Fewest bytes wins.
For example, n=25 gives 12 because 25 can be expressed as
(5)^2  + (0)^2
(4)^2  + (3)^2
(3)^2  + (4)^2
(0)^2  + (5)^2
(-3)^2 + (4)^2
(-4)^2 + (3)^2
(-5)^2 + (0)^2
(-4)^2 + (-3)^2
(-3)^2 + (-4)^2
(0)^2  + (-5)^2
(3)^2  + (-4)^2
(4)^2  + (-3)^2

Here are the values up to n=25. Be careful that your code works for n=0.
0 1
1 4
2 4
3 0
4 4
5 8
6 0
7 0
8 4
9 4
10 8
11 0
12 0
13 8
14 0
15 0
16 4
17 8
18 4
19 0
20 8
21 0
22 0
23 0
24 0
25 12

Here are the values up to n=100 as a list.
[1, 4, 4, 0, 4, 8, 0, 0, 4, 4, 8, 0, 0, 8, 0, 0, 4, 8, 4, 0, 8, 0, 0, 0, 0, 12, 8, 0, 0, 8, 0, 0, 4, 0, 8, 0, 4, 8, 0, 0, 8, 8, 0, 0, 0, 8, 0, 0, 0, 4, 12, 0, 8, 8, 0, 0, 0, 0, 8, 0, 0, 8, 0, 0, 4, 16, 0, 0, 8, 0, 0, 0, 4, 8, 8, 0, 0, 0, 0, 0, 8, 4, 8, 0, 0, 16, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 8, 4, 0, 12]

Fun facts: The sequence contains terms that are arbitrarily high, and the limit of its running average is π.
Leaderboard:

    var QUESTION_ID=64812,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/64812/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
    body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
     <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Wait, what?? "The sequence contains terms that are arbitrarily high, and the limit of its running average is π."

@StewieGriffin The two statements are consistent. Consider the sequence 1,0,2,0,0,3,0,0,0,4,0,0,0,0,5,.... Cutting the sequence off after any nonzero number, the average so far is 1. And, the runs of 0's have less and less impact later in the sequence.

I know it's consistent.. =) I had checked the 10.000 first numbers when I posted the comment. What I don't get is: Why on earth does it equal Pi?

@StewieGriffin The sum of the terms up to N corresponds to the points (a,b) with a^2+b^2<=N. These are the lattice points in the circle of radius sqrt(N), whose area is πN.

@xnor and there goes the magic:(

@xnor damn, nice connection there.

Python (59 57 56 bytes)
lambda n:0**n+sum((-(n%(x-~x)<1))**x*4for x in range(n))

Online demo
As with my CJam answer, this uses Möbius inversion and runs in pseudoquasilinear time.
Thanks to Sp3000 for 2 bytes' savings, and feersum for 1.

Those parentheses are annoying.

@ThomasKwa, tell me about it. The thing which really surprised me, in one of the versions I passed through on the way to the first one I posted, was that -1**x is always -1. I expected the -1 to be a single integer literal token rather than a low-precedence unary minus followed by a one.

Congrats on the bounty! Your code is shorter than anything I had come up with. Your solution is based on a totally new and unexpected mathematical idea, and it brings me joy to that this is possible even in such a straightforward-looking challenge .The Mobius-inverse result is quite pretty and I took the pleasure of deriving a proof for myself.

1 byte can be saved by moving the multiplication by 4 to after **x.

@PeterTaylor Can you elaborate how your algorithm works/can you point me to a resource? I cannot quite see how you can apply the möbius inversion to number of sums of suqares problem.

@flawr, I haven't worked through the details, but (as mentioned in my CJam answer), the relationship is given in OEIS. MathWorld's discussion of the relevance of primes equal to 1 and 3 mod 4 probably provides enough ammunition to tackle the proof.

@PeterTaylor Thank you very much!

If Python's boolean/number parsing works like JS's, +!n should work in place of 0**n.

@ETHproductions, Python is quite idiosyncratic. It has and instead of &&, not instead of !, doesn't have ++ or ?:...

Python 2, 44 bytes
f=lambda n,x=1:+(x>n)or(n%x<1)-f(n,x+2)/4<<2

This is almost the same as xsot's solution (which is based on Peter Taylor's solution), but saves 8 bytes by simplifying the way signs are handled.
Note that for a full program, we can save 2 bytes in the function without incurring a cost outside the function:
f=lambda n,x=1:x>n or(n%x<1)-f(n,x+2)/4<<2
print+f(input())

Two additional bytes for a full program this way:
n=input()
f=lambda x:x>n or(n%x<1)-f(x+2)/4<<2
print+f(1)

For n > 0 there is a very legible 40-byte solution:
f=lambda n,x=1:n/x and(n%x<1)*4-f(n,x+2)

Congrats for winning the bounty! The recursive subtraction is a clean and short way to express the alternating sum for odd divisors without needing to extract a sign from the divisor itself. Also, credit to xsot for streamlining Peter Taylor's solution to a recursive one with clever handling of n=0.

Mathematica, 13 bytes
If built-ins are allowed, this is how to do it in Mathematica.
2~SquaresR~#&

For 0 < = n <= 100
2~SquaresR~# & /@ Range[0, 100]

{1, 4, 4, 0, 4, 8, 0, 0, 4, 4, 8, 0, 0, 8, 0, 0, 4, 8, 4, 0, 8, 0, 0,
0, 0, 12, 8, 0, 0, 8, 0, 0, 4, 0, 8, 0, 4, 8, 0, 0, 8, 8, 0, 0, 0, 8,
0, 0, 0, 4, 12, 0, 8, 8, 0, 0, 0, 0, 8, 0, 0, 8, 0, 0, 4, 16, 0, 0,
8, 0, 0, 0, 4, 8, 8, 0, 0, 0, 0, 0, 8, 4, 8, 0, 0, 16, 0, 0, 0, 8, 8,
0, 0, 0, 0, 0, 0, 8, 4, 0, 12}

Because of course Mathematica has a built-in for this.

J, 16 bytes
+/@,@:=+&*:/~@i:

This is a monadic verb (in other words, a unary function).
Try it online or see it pass all test cases.
Explanation
+/@,@:=+&*:/~@i:  Denote input by n
              i:  The array of integers from -n to n
           /~@    Take outer product wrt the following function:
       +           the sum of
        &*:        squares of both inputs
                  This results in a 2D array of a^2+b^2 for all a, b between -n and n
      =           Replace by 1 those entries that are equal to n, and others by 0
   ,@:            Flatten the binary matrix
+/@               Take its sum

Pyth, 13 bytes
/sM^^R2}_QQ2Q

Test suite
/sM^^R2}_QQ2Q
                 Q = eval(input())
       }_QQ      Inclusive range from -Q to Q (all possible a and b)
    ^R2          Map to their squares
   ^       2     Form all pairs
 sM              Sum pairs
/           Q    Count occurances of Q

Late, but I don't think you need the last Q.

Python 2, 69 55 53 52 bytes
f=lambda n,x=1:+(x>n)or(2-x%4)*(n%x<1)+f(n,x+2)/4<<2

This is a recursive function based off Peter Taylor's excellent solution.

This is a great improvement. But, there is still a way to make it shorter, and I encourage you to look for it.

@xnor Another byte down. I hope you don't have any more tricks up your sleeves.

Whoa, that operator precedence. I don't have this trick but I have a different, bigger one.

I don't know whether I should make an answer of it, it's just your solution plus one trick: f=lambda n,x=1:+(x>n)or(n%x<1)-f(n,x+2)/4<<2. Also, I guess we don't care about exceeding the default maximum recursion depth?

(For positive n, can simplify f=lambda n,x=1:n/x and(n%x<1)*4-f(n,x+2))

@xnor Is that the same idea as yours?

@MitchSchwartz I think that's an incredible improvement worthy of the bounty and likely the final optimisation xnor had in mind.

@MitchSchwartz Yes, that's the optimization I was thinking of! And xsot's /4<<2 trick makes it shorter than what I had.

Julia, 40 bytes
n->n>0?4sum(i->(n-i^2)^.5%1==0,1:n^.5):1

Ungolfed:
function f(n)
  if n==0
    return 1           # Handle special case of n=0
  else
    m=0                # Start the counter at zero
    for i=1:sqrt(n)    # Loop over the values (i) whose squares are
                       # less than n (except zero)
      k=sqrt(n-i^2)    # Find k such that n=k^2+i^2
      if k==floor(k)   # if k is an integer, we've found a pair
        m+=4           # Add one for each of k^2+i^2, (-k)^2+(-i)^2, and the other two
      end
    end
    return m           # Return the resulting count
  end
end

Note that the loop doesn't include i==0, because when n is a square, it's already included by i=sqrt(n), and there are only four, not eight, for that form (0^2+k^2, 0^2+(-k)^2, k^2+0^2, (-k)^2+0^2).

CJam, 25 23 bytes
Zri:R#Ym*{Rf-Yf#:+R=},,

This is a theoretical solution that requires O(9n) time and memory for input n.
At the cost of one extra byte – for a total of 24 bytes – we can reduce the complexity to O(n2):
ri:R)Y*Ym*{Rf-Yf#:+R=},,

Try it online!
How it works
Either
Z                  Push 3.
 ri:R              Read an integer from STDIN and save it in R.
     #             Compute 3**R.

or
ri:R               Read an integer from STDIN and save it in R.
    )Y*            Add 1 and multiply by 2.

Then
Ym*                Take the second Cartesian power, i.e., compute all pairs.
   {          },   Filter the pairs:
    Rf-              Subtract R from each.
       Yf#           Square the differences.
          :+         Add the squares.
            R=       Compare with R.
                   If = pushed 1, keep the pair.
                ,  Count the kept pairs.

And at a saving of one byte it's possible to get the complexity down to Õ(n)

Yes, I saw. That's amazing.

CJam (25 24 22 21 bytes)
{:X!X{X\2*)%!4*\-}/z}

Online demo
This runs in pseudoquasilinear time* and uses the statement from the OEIS that

Moebius transform is period 4 sequence [ 4, 0, -4, 0, ...]. - Michael Somos, Sep 17 2007

The input 0 is obviously a special case (Möbius tranforms and annihilators don't go well together), but ended up only costing one char.
* Pseudo- because it's quasilinear in the value of the input, not the size of the input; quasi because it does Theta(n) operations on integers of size on the order of n; a b-bit mod operation should take b lg b time, so overall this takes Theta(n lg n lg lg n) time.

Python 3, 68 61 60 bytes
lambda n:0**n+4*sum(i**.5%1+(n-i)**.5%1==0for i in range(n))

Using two nested list comprehensions is too expensive. Instead, this checks if both coordinates on the circle of radius sqrt(n) are integers.
Peter Taylor has beaten this with a Moebius-inversion based approach.

Well done. I was tinkering with a recursive function but couldn't resolve n=0 elegantly.

Japt, 42 37 33 bytes
Japt is a shortened version of JavaScript. Interpreter
V=Un oU+1;Vr@X+(Vf_p2 +Y*Y¥U)l ,0

How it works
           // Implicit: U = input number
V=Un oU+1  // Set variable V to range(-U, U+1). Ends up like [-U,-U+1,...,U-1,U]
Vr@    ,0  // Reduce each item Y in V with this function, starting at 0:
X+(     l  //  Return the previous value X + the length of:
Vf_p2      //   V filtered by items Z where Z*Z
+Y*Y==U)   //    + Y*Y equals U.
           // This ends up as the combined length of all fitting pairs of squares.
           // Implicit: return last expression

Perhaps there's a better technique; suggestions are welcome.

Haskell, 42 bytes
f n|q<-[-n..n]=sum[1|a<-q,b<-q,a*a+b*b==n]

Usage exapmle:
*Main> map f [0..25]
[1,4,4,0,4,8,0,0,4,4,8,0,0,8,0,0,4,8,4,0,8,0,0,0,0,12]
*Main>

Binding q in a guard is clever, I'll remember this trick.

Julia, 89 79 63 bytes
g(x)=cos(π*x^.5)^2÷1
a(n)=(n==0)+4sum([g(i)g(n-i)for i=1:n])

This is a named function a which accepts an integer and returns a float. It calls a helper function g.
Ungolfed:
function g(x::Integer)
    floor(cos(π*sqrt(x))^2)
end

function a(n::Integer)
    (n == 0) + 4*sum([g(i)*g(n-i) for i=1:n])
end

The approach here uses a simplification of Wesley Ivan Hurt's formula listed on OEIS. The simplification was found by Glen O, the very same person who shaved 26 bytes off of this answer!

Use x^.5 rather than sqrt(x) to save 3 bytes. And (n==0) saves 2 bytes over 1÷(n+1). And you can save 4 more characters by using cos(π*sqrt(x))^2÷1 rather than floor(cos(π*sqrt(x))^2). Also, use 1:n/2 rather than 1:n÷2, because there's no harm using a float in g(x) and it'll be locked to the integers for i anyway. And sum(i->g(i)g(n-i),1:n/2) will shave some more characters, too.

@GlenO Great suggestions, thanks. The sum trick fails for n=0 though, so I kept array comprehension.

So, it can be recovered - if you let the i=0 case happen in the sum, you can switch the sign on 4g(n). So (n==0)-4g(n)-4g(n/2)+8sum(i->g(i)g(n-i),0:n/2), which will not run into the error. But you can do even better, by noting the symmetries - (n==0)+4sum([g(i)g(n-i)for i=1:n])

@GlenO That simplification is seriously genius. I recommend you submit that as an alternative formula for the sequence on OEIS!

Octave, 28 bytes
@(n)nnz((a=(-n:n).^2)'+a==n)

Python 3, 93 62 69 bytes
Itertools wasn't working so I used two ranges again, but moved the range out to save bytes.
Edit: Previous code didn't actually work, since I defined range over n before I defined n.
lambda n:sum(i*i+j*j==n for i in range(-n,n+1)for j in range(-n,n+1))

Pyth, 16 15 bytes
lfqQs^R2T^}_QQ2

Try it online in the Pyth Compiler.
How it works
lfqQs^R2T^}_QQ2

          }_QQ   Compute the inclusive range from -Q to Q (input).
         ^    2  Take the second Cartesian power, i.e., compute all pairs.
 f               Filter; for each T in the list of pairs:
     ^R2T          Compute the squares of T's elements.
    s              Add the squares.
  qQ               Compare the sum with Q.
                 If q returned True, keep T.
l                Count the kept pairs.

TI-BASIC, 23 bytes
sum(seq(Σ(X²+Y²=Ans,X,-Ans,Ans),Y,-Ans,Ans

Pretty straightforward. Σ( is summation.
Strangely, sum(seq(sum(seq( throws an ERR:ILLEGAL NEST, and so does Σ(Σ(, but sum(seq(Σ( is fine. I chose to put the Σ( on the inside to save a close-paren.

What's the difference between sum and Σ?

@alephalpha Σ( takes a summation, adding up all of the X²+Y²=Ans from values of X between -Ans and Ans. sum( is sum of a list, so we need to create the list first using seq(...,Y,-Ans,Ans

JavaScript (ES6), 66 60 bytes
n=>eval("for(r=0,a=~n;a++<n;)for(b=~n;b++<n;)r+=a*a+b*b==n")

6 bytes saved thanks to @edc65!
Explanation
n=>eval(`              // use eval to allow for loops in an unparenthesised arrow function
  for(r=0,             // r = number of pairs
    a=~n;a++<n;        // a = first number to square
  )
      for(b=~n;b++<n;) // b = second number to square
        r+=a*a+b*b==n  // add one to the result if a^2 + b^2 == n
                       // implicit: return r
`)

Test

n = <input type="number" oninput='result.innerHTML=(

n=>eval("for(r=0,a=~n;a++<n;)for(b=~n;b++<n;)r+=a*a+b*b==n")

)(+this.value)' />

60: n=>eval('for(r=0,a=~n;a++<n;)for(b=~n;b++<n;)r+=a*a+b*b==n')

@edc65 Nice! I didn't think of using eval to put the for loops into an arrow function without parentheses. I also forgot about the ~ operator haha.

Candy, 17 14 bytes
Input pushed onto stack initially
~TbAT1C(sWs+Aeh)Z
~T0C(sWs+Aeh)Z
peekA    # copy arg from stack to register A
range2   # create double sided range on stack, -A, 1-A, ... A-1, A
digit0   # prefix argument to 'cart',
cart     # cartesian product of current stack(0), and other stack(0)
while    # while stack not empty
  sqr    # pop and square and push
  swap   # swap two stack elements
  sqr    # pop and square and push
  add    # pop and pop and add and push
  pushA  # push original argument
  equal  # equality test 0/1
  popAddZ  # Z := Z + pop
endwhile
pushZ    # push Z onto stack, will be output to stdout on termination

CJam, 28
qi_mF{3a>},{~)\4%2-&}%4+:*1?

Not really short, but efficient. E.g. the result for 15625 is instantly 28. Uses the factorization-based formula from OEIS.
Try it online
Explanation:
qi       read input and convert to integer
_        make a copy (will be used to handle the 0 case at the end)
mF       factorize into [prime exponent] pairs
{…},     filter the array of pairs
  3a>    with the condition that the pair is greater than [3]
          which means the prime factor must be ⩾3
{…}%     transform each pair as follows:
  ~      dump the prime factor and exponent onto the stack
  )      increment the exponent
  \      swap with the prime
  4%     get the remainder mod 4 (it will be 1 or 3)
  2-     subtract 2 (resulting in -1 or 1)
  &      bitwise AND with the incremented exponent (see below)
4+       append a 4 to the array
:*       multiply all
1?       if the input was 0, use 1, else use the above result

Some details about the calculation:

if the prime is 1 mod 4, the code calculates (exponent + 1) & -1, which is exponent + 1
if the prime is 3 mod 4, the code calculates (exponent + 1) & 1, which is 0 if the exponent is odd, and 1 if even

All these values multiplied together and multiplied by 4 are exactly the OEIS formula.

Python 2, 68 bytes
def x(n):r=range(-n,n+1);print sum(a*a+b*b==n for a in r for b in r)

Defines a function called x() that takes a number n.
Try it online.
http://ideone.com/aRoxGF

You are missing a print or return statement.

Thanks, I completely forgot.  The link has the print statement though.  I edited my code while I was making the code.

Ok, no worries. But this also seems to give incorrect results for n=0 and n=1 (0 and 2 instead of 1 and 4). Maybe the range limits need adjusting?

@Zgarb Yeah, they should end at n+1.

This looks pretty short, but knowing xnor I don't think it'll be this simple.

I tested it (the new version) for all of the values he gave, that is 0-25.  They were all correct.  I haven't tested it for anything else though.

I've tested a version of this, slightly modified to run on Python 3, from 0 to 101 (values provided by the OEIS). It works for all of them.

@RikerW I wasn't questioning the validity; I was saying xnor's bounty means there's a shorter but hard-to-find solution.

I'll look for it.

Pyth, 41 35 33 30 27 bytes
Try it online.
Edit: Thanks to isaacg, I got m and *F to work! YES!
?Q*F+4m.&tt%ed4hhdr-PQ2 8 1
                                (implicit) Q = input()
?Q                              If Q != 0
      m                           Map to d (exponent, prime) from ...
                  r-PQ2 8         run-length-encoded(PQ with 2's removed)
       .&                           Bitwise and
           %ed4                       d[-1] % 4
         tt                           -2
                hd                  with d[0]
               h                      +1
    +4                            Append 4 to the resulting array
  *F                              Then multiply it all together
                          1     Else 1

Edit: Put the bitwise and back in for more byte savings! Also I removed all the "Formerly" stuff. It was starting to get cluttered.
Thanks to aditsu and his CJam solution, and to maltysen and his tips (One day I will get m*Fd to work. One day...)
J4Vr-PQ2 8=J*J.&tt%eN4hhN;?QJ1
                                (implicit) Q=input()
J4                              J=4
    -PQ2                        Remove all 2's from the prime factorization of Q
   r     8                      run-length encode (exponent, prime factor)
  V                      ;      For N in range( the above ):
          =J*J                      J = J * ...
                tt%eN4                N[-1] mod 4 -2
                      hhN             (exponent + 1)
              .&                    bitwise and
                          ?QJ1  if Q != 0 print(J) else print(1)

Note that,

if the prime is 1 mod 4, we get -1 & (exponent + 1), which is exponent + 1

but if the prime is 3 mod 4, we get 1 & (exponent + 1), which is 0 if the exponent is odd, and 1 if even

Multiply it all together (times 4 at the beginning) and we get the number of sums of two squares that add up to our input.

APL, 23 20 19 bytes
{+/⍵=∊∘.+⍨×⍨0,,⍨⍳⍵}

Explanation:
{+/⍵=∊∘.+⍨×⍨0,,⍨⍳⍵}        Monadic function:
                 ⍳⍵          1 2 3 ... ⍵
               ,⍨            Duplicate
             0,              Concatenate to 0
          ×⍨                 Square everything
      ∘.+⍨                   Make an addition table
     ∊                       Flatten
   ⍵=                        1s where equal to the input
 +/                          Sum up the 1s

Other than the fact that APL doesn't have J's i: (numbers from -n to n) function, this works pretty much like the J answer.
We can't use a train because getting the -\⍳2×⍵ to not parse as (-\) ⍳ (2×⍵) would cost three bytes; similarly with other pair of atops. All those parentheses make the regular function shorter.
Try it here. The output of 1 means all values match.

PARI/GP, 34 28 bytes
Using generating functions:
Saved 6 bytes thanks to Mitch Schwartz.
n->sum(i=-n,n,x^i^2)^2\x^n%x

Using built-ins, 33 bytes (saved 1 byte thanks to Mitch Schwartz.):
n->if(n,2*qfrep(matid(2),n)[n],1)

qfrep(q,B,{flag=0}): vector of (half) the number of vectors of norms from 1 to B for the integral and definite quadratic form q. If flag is 1, count vectors of even norm from 1 to 2B.

matid(2) saves a byte.

And down to 28 for the generating function approach: n->sum(i=-n,n,x^i^2)^2\x^n%x

Matlab 41 bytes
Even smaller as the previous answers
@(n)nnz(~mod(sqrt(n-(1:n^.5).^2),1))*4+~n

Essentially Agawa001's answer with power and sqrt replaced

Python, 57 bytes
Nice challenge. Unfortunately I'm not getting it shorter than this at the moment.
lambda n:0**n+sum(2-d%4for d in range(1,n+1)if d%2>n%d)*4

Python, 133 129 bytes
from itertools import*
n=input()
l=[];s=0
for i in range(-n,n+1):l.append(i**2)
for j in product(l,l):
 if sum(j)==n:s+=1
print s

This demonstrates the use of itertools cartesian product. Try it online

@Mego I tried, I don't think there is anything to further golf. I will take that part out if you insist.

JavaScript, 89 bytes
n=prompt()
p=Math.pow
for (x=c=(+n?0:1);x<=n;x++)if(x&&p(n-p(x,2),.5)%1===0)c+=4
alert(c)

I know this isn't the shortest JavaScript answer even if I were to remove the i/o lines, but I do think it is the best performing JS answer giving me the result for a million within a few seconds (ten million took about a minute).

Can you use == instead of ===?

I could, just using best practices, ha ha.

Matlab, 72 bytes
n=input('');m=fix(sqrt(n));m=(-m:m).^2;disp(nnz(bsxfun(@plus,m,m')==n))

You don't need disp in this challenge Luis! =)

@StewieGriffin Thanks! But in this case it's a program, not a function. So according to the accepted answer in your link it's needed, isn't it?

Matlab, 63 50 bytes
@(y)nnz(~mod(sqrt(y-power((1:sqrt(y)),2)),1))*4+~y

This does beat the other same-entitled code, thus I put it :D.
The program finds the positive integer solutions then multiply by 4 to encompass negative ones.
It can perform all 25 first test cases
for i=1:25 ans(i)
end

   1

   4

   4

   0

   4

   8

   0

   0

   4

   4

   8

   0

   0

   8

   0

   0

   4

   8

   4

   0

   8

   0

   0

   0

   0

   12

You don't need disp in this challenge! =)

thanks @StewieGriffin i did include it just as a fair-game relating to luis' one

Tips: When you're planning on posting the results from MATLAB, use format compact =)

PHP, 80 Bytes
for($m=-$a=1+$argv[1];++$m<$a;)for($n=-$a;$n++<$a;)$c+=$a-1==$m**2+$n**2;echo$c;

$c+=condition; instead of if(condition)$c++; (-4) Do you feel stalked? :D pre-increment on $m and $n will improve speed a bit.

PHP, 70 bytes, not competing
for($x=-1;$x++<=$n=$argv[1];)$s+=(-($n%($x-~$x)<1))**$x*4;echo$n?$s:1;

algorithm stolen from one of the Python answers ... I forgot which one; wanted to at least partially understand what´s happening before I posted.

for(;$x<=$n=$argv[1];)$s+=(-($n%(2*$x+1)<1))**$x++*4;echo$n?$s:1; saves 5 Bytes. $x-~$x is equal to 2*$x+1 and you can now start without assigning the variable.

ASP, 53 + 4 = 57 bytes
#show N:N=#count{o(A,B):k=A**2+B**2,A=-k..k,B=-k..k}.

Answer Set Programming is a logical language, similar to prolog.
I use here the Potassco implementation, clingo.
Input is taken from parameters (-ck= is 4 bytes long). Call example:
clingo -ck=25

Output sample:
12

You can try it in your browser ; unfortunately, this method doesn't handle call flags, so you need to add the line #const k=25 in order to make it work.

Add++, 31 bytes
D,f,@,.5^1+iR2€Ω^d0BFB]d‽+A€=¦+

Try it online!
How it works
This defines a function, \$f\$, that takes the input, \$x\$, as an argument and returns the correct output. We start by yielding \$y := \lfloor\sqrt{x}+1\rfloor\$. We then push the range \$a := [1, 4, ..., y^2]\$, the list of square numbers up to the smallest square number larger than \$x\$. We then duplicate this array and push \$0\$ to the stack. At this point, the stack looks like this, for an input of \$25\$:
[[1 4 9 16 25 36] [1 4 9 16 25 36] 0]

We then collect these values into a single list, which yields the list of \$n^2\$ for each \$n \in [-y, y]\$. We then duplicate this list and operate the table operator over the addition command. The table operator takes a dyad, \$g(p, q)\$, and two arrays, \$A\$ and \$B\$. It then takes the Cartesian Product of \$A\$ and \$B\$ and iterates \$g(a, b)\$ over each pair \$(a, b)\$ where \$a \in A\$ and \$b \in B\$.
In this code, this yields the array \$\big[a^2+b^2 \: | \: a, b \in [-y, y]\big]\$. We then compare each element of this list with the input, yielding a boolean array. Finally, we count the number of \$1\$s in this array by taking its sum, and returning that total.
Most of the code should be understandable when paired with the explanation. A few of the overlooked commands:

Ω : The reverse operator. Takes a dyad and reverses the order of the arguments
‽ : The table operator, as described above.
¦ : The fold operator. Takes an array and a dyad and reduces by the dyad. ¦+ is an alias for sum.

MathGolf, 9 bytes
╤■mæ²Σk=Σ

Try it online.
Explanation:
╤         # Take the (implicit) input-integer, and push a list in the range [-input, input]
 ■        # Take the cartesian product of this, creating a list of all possible pairs
  mæ      # Map these pairs to, using the following four commands:
    ²     #  Take the square of both values in the pair
     Σ    #  Sum those
      k=  #  And check whether it's equal to the input-integer (1 if truthy; 0 if falsey)
  Σ       # After the map, sum the list
          # (after which the entire stack joined together is output implicitly)

05AB1E, 7 bytes
(ŸãnOQO

Try it online or verify the test cases in the range \$[0,100]\$.
Explanation:
(        # Get the negative of the (implicit) input-integer
 Ÿ       # Push a list in the range [(implicit) input-integer, -input]
  ã      # Get the cartesian product of this list, creating all possible pairs
   n     # Square each value in each pair
    O    # Sum each inner pair
     Q   # Check for each sum whether it's equal to the (implicit) input-integer
         # (1 if truthy; 0 if falsey)
      O  # And sum those
         # (after which the result is output implicitly)

Japt -x, 11 bytes
õUn)ï £¶Xx²

Try it

Jelly, 7 bytes
rNp`²§ċ

Try it online!
How it works
rNp`²§ċ - Main link. Takes n on the left
 N      - Yield -n
r       - Take the range [-n, -n+1, ..., -1, 0, 1, ..., n-1, n]
   `    - Use this list for both arguments for:
  p     -   Cartesian product
    ²   - Square each number
     §  - Take the sums of each pair
      ċ - Count the number of times n appears

C, 224 219 182 175 158 bytes
Non-golfed version (with descriptive variables):
#include <math.h>

main (argc, argv)
    char **argv;
{

    int n, count, max, i, j;
    n = atoi (argv[1]);
    count = 0;
    max = sqrt ((float) n);

    for (i = -max; i <= max; i++)
        for (j = -max; j <= max; j++)
            if (i * i + j * j == n)
                count++;

    printf ("%d", count);
}

Golfed version (with short variables):
#include<math.h>
main(c,v)char**v;{int n,o,x,i,j;n=atoi(v[1]);o=0;x=sqrt((float)n);for(i=-x;i<=x;i++)for(j=-x;j<=x;j++)if(i*i+j*j==n)o++;printf("%d",o);}

Update Sorry about the multiple edits, I'm learning how to abuse K&R-style C ;)

You can remove the sqrt and just set the forloop bounds to -n and +n. This calculates a lot more but is shorter ;)

Perl 5, 52 bytes
56 bytes:
$n=pop;for$a(@a=-$n..$n){map$i+=$_*$_+$a*$a==$n,@a}say$i

If output can be in base 1, then 52 bytes:
$n=pop;for$a(@a=-$n..$n){print$_*$_+$a*$a==$n for@a}

Why waste so many bytes using an array? You can do the -$n..$n in the for statement...

@WouterVerheist I use @a twice, and wouldn't save bytes writing -$n..$n twice. However, presumably I can incorporate the assignment to @a into the first time it's used, which will save 3 bytes. If I have an opportunity to test it and remember to do so, I'll do so and revise this answer.

Ah, yes, missed that. I must be blind.

@WouterVerhelst But thanks for the tip: you saved me three bytes.

Python, 76 74 bytes
I'm sure this can be golfed more, but I need to get back to work.
lambda n:sum([1for a in range(-n,n+1)for b in range(-n,n+1)if a*a+b*b==n])

Try it online
Thanks to @mathmandan for taking off 2 bytes.

Quick note: a*a+b*b is shorter than a**2+b**2.  Also the square brackets aren't required here, so you can get down to 72 bytes.  (FYI, it looks like def f(n):r=range(-n,n+1);print sum(1for j in r for i in r if i*i+j*j==n) is also the exact same score.)

Thanks. The a*a is almost obvious - stupid I didn't see that. The brackets are needed for the comprehension to work. So it's down to 74. Also putting lambda n,r=range results in the same length. Too bad...

Without the square brackets, it won't make a list, but it'll make a generator, which works fine with sum.  https://docs.python.org/2/tutorial/classes.html#generator-expressions (Removed square brackets and tested fine in 2.7.4.)

Ruby, 66 58 56 54 bytes
->n{r=-n..n;r.map{|x|r.count{|y|n==x*x+y*y}}.reduce:+}

Thanks to sherlock9.
56 bytes
->n{r=-n..n;r.map{|x|r.count{|y|n==x**2+y**2}}.reduce:+}

58 bytes
->n{c=0;r=(-n..n);r.map{|x|c+=r.count{|y|n==x**2+y**2}};c}

66 bytes
->n{c=0;(-n..n).each{|x|c+=n.downto(-n).count{|y|n==x**2+y**2}};c}

Ungolfed:
-> n {
  r = -n..n
  r.map { |x|
    r.count { |y|
      n == x*x + y*y
    }
  }.reduce:+
}

Usage:
->n{r=-n..n;r.map{|x|r.count{|y|n==x*x+y*y}}.reduce:+}[25]
=> 12

You can shave two bytes by using x*x+y*y

C++, 175 bytes
#include<iostream> using namespace std; int main() {int i,j,k=0,n; cin>>n; for(i=1;i<n;++i) for(j=1;j<n;++j) if(i*i+j*j==n) ++k; for(i=1;i<=n;++i) if(i*i==n) ++k; cout<<4*k;}

Ungolfed
#include<iostream>
using namespace std;
int main()
{
int i,j,k=0,n;
cin>>n;
for(i=1;i<n;++i)
 for(j=1;j<n;++j)
  if(i*i+j*j==n)
   ++k;
for(i=1;i<=n;++i)
 if(i*i==n)
  ++k;
cout<<4*k;
}

I hope it's okay now.

Not quite. 1. Given input of 0, it gives output of 0. That's a special case, and should be 1. 2. It doesn't compile as is. The #include needs a newline before the following statement. 3. Some tips: you can remove 11 chars just by cutting out unnecessary whitespace. You can remove more with some basic transformations like for(i=1;i<n;++i) being equivalent to for(i=0;++i<n;). If you change the range of the loop over j then I think you can eliminate the second loop over i entirely.

Swift 2.0, 110 108 107 bytes
var n=Int(readLine()!)!,c=0;for(var i = -n;i<=n;i++){for(var j = -n;j<=n;j++){if i*i+j*j==n{c++}}};print(c)

First attempt

I think you could save many bytes by removing whitespace.

I can only remove two but thanks!

What about when you create the variables?

The online swift compiler gives errors in that cases, dont have a mac close atm

Axiom 115 bytes
g(n)==(v:INT:=truncate(sqrt(n)::Float);c:=0;for i in -v..v repeat for j in -v..v repeat if i^2+j^2=n then c:=c+1;c)

ungolfed
gg(n:NNI):NNI==
   v:NNI:=truncate(sqrt(n)::Float)
   c:NNI:=0
   for i in -v..v repeat
      for j in -v..v repeat
          if i^2+j^2=n then c:=c+1
   c

results
(5) -> [i,g(i)]  for i in 0..25
   Compiling function g with type NonNegativeInteger -> NonNegativeInteger
   (5)
   [[0,1], [1,4], [2,4], [3,0], [4,4], [5,8], [6,0], [7,0], [8,4], [9,4],
    [10,8], [11,0], [12,0], [13,8], [14,0], [15,0], [16,4], [17,8], [18,4],
    [19,0], [20,8], [21,0], [22,0], [23,0], [24,0], [25,12]]
                                      Type: Tuple List NonNegativeInteger

dobious results
(13) -> g(10018)
   (13)  8
                                                    Type: PositiveInteger
(14) -> g(10019)
   (14)  0
                                                 Type: NonNegativeInteger
(15) -> g(10020)
   (15)  0

C++, 81 bytes
#define F(x) for(int x=~n;x++<n;)
void f(int n,int&r){r=0;F(a)F(b)r+=a*a+b*b==n;}

Returns via reference parameter. Simply two ranges over [-n,n], so it works for n=0.

Husk, 8 bytes
#¹´×+m□ṡ

Try it online! or Verify first 25 values
Husk, 8 bytes
#¹mṁ□π2ṡ

Try it online!

Thunno 2 S, 7 bytes
ṄIDṖ²ʂ=

Try it online!
Explanation
ṄIDṖ²ʂ=  # Implicit input
ṄI       # Push [-input..input]
  DṖ     # Cartesian product
    ²ʂ   # Square and sum
      =  # Equals input?
         # Sum the list
         # Implicit output


text:
Chemical sentences! Encrypting
Background
You are bored in class, and having exhausted all the possible things to write on a standard calculator (Like 8008135) you turn to the periodic table. You want to figure out if you can write your message using the shorthand for chemical elements.
This is the inverse of this challenge.

The Challenge
Input: A sentence, or a word.
Output: The placement of each chemical element used in the sentence.
If the sentence / word can not be created, you must return blank, False or throw an error.
Test cases
Input 1:
fire

Output 1:
9 53 75

Input 2:
Crazy Input

Output 3:
False

Input 3:
american ass

Output 3:
95 68 53 20 11 16 16

Note: There is no problem with a element being in two words as shown in the last example. American can be written as 95 68 53 20 7 but then Ass is impossible to write due to the lack of an A in the table. In other words discard all whitespaces (but they must be allowed) in input.
Note Standard loopholes are not allowed including built in periodic tables and libraries.
Scoring
Submissions will be scored in bytes. I recommend this website to keep track of your byte count, though you can use any counter you like.
This is code-golf, so the lowest score wins!

Is the use of periodic table built-ins allowed?

I forgot Mathematica had such capabilities! On one hand this gives and advantage to a very few select languages, on the other hand hardcoding these will be a pain. Being the more experienced what do you think @Dennis?

Encoding the table is the biggest part of the challenge, so a built-in table would, in my opinion, trivialize it for some languages. Personally, I'd disallow them.

Related.

Yes. Updated it now.


text:
Chemical sentences! Decrypting
Background
You are sitting in chemistry class and your friend keep sending you these strange letters. It is your job to decrypt the messages into words.
This is the inverse of this challenge.

The Challenge
Input: A list or a string of integers from 1 to 118.
Output: The words for each chemical element if possible. Otherwise return False, throw an error, or blank. Note in your program 0 must return a whitespace or newline. Ignore all integers not in range.
Test cases
Input 1:
9 53 75

Output 1:
fire

Input 2:
91 120 91

Output 2:
papa

Input 3:
9 53 75 0 53 16 0 9 92 7

Output 3:
fire is fun

Note: Again no built in functions for generating the periodic system or external libaries. Standard loopholes are not allowed.
Scoring
Submissions will be scored in bytes. I recommend this website to keep track of your byte count, though you can use any counter you like.
This is code-golf, so the lowest score wins!

Related.

Borderline dupe

Does the output have to be in lowecase or can it be mixed case (for example FIRe IS FUN or PaPa)?

Mixed cases are fine =)

Pyth, 264 bytes
s@L+" "-R0+c"h0helibeb0c0n0o0f0nenamgalsip0s0clark0casctiv0crmnfeconicuzngageassebrkrrbsry0zrnbmotcrurhpdagcdinsnsbtei0xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw0reosirptauhgtlpbbipoatrnfrraacthpau0nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcn"2c"uutfl0uuplv0uusuuo"3rz7

Use packed str?

@isaacg Last time I tried to use it it was all buggy :(

TIL that the periodic table contains "clark".

But no "kent" :-(

Par, 261 bytes
` 0h0helibeb0c0n0o0f0nenamgalsip0s0clark0casctiv0crmnfeconicuzngageassebrkrrbsry0zrnbmotcrurhpdagcdinsnsbtei0xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw0reosirptauhgtlpbbipoatrnfrraacthpau0nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcn`2%`uutfl0uuplv0uusuuo`3%+l✶´gΣ'0-

One byte is used per character, even Σ, since a specialized encoding is used. See here.
Input is Lisp-style, e.g. (9 53 75 0 53 16 0 9 92 7)
` 0h0hel...n`  ## Elements until Uut
2%             ## Split into pieces of size 2
`uutfl0u...o`  ## Elements from Uut
3%             ## Split into pieces of size 3
+              ## Combine into list of elements
l✶             ## Read array of numbers
´g             ## Find the element at each index
Σ              ## Concatenate
'0-            ## Remove all 0's

Python 2.x, 295 bytes
Golfed code:
import re;print''.join([re.findall('[A-Z ][a-z]*',' HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo')[e]for e in i])

NB: to shave 8 bytes, output for this version is in mixed caps (doesn't break any rules), missing the .lower() ending

387 bytes
Golfed code:
print''.join([' ,h,he,li,be,b,c,n,o,f,ne,na,mg,al,si,p,s,cl,ar,k,ca,sc,ti,v,cr,mn,fe,co,ni,cu,zn,ga,ge,as,se,br,kr,rb,sr,y,zr,nb,mo,tc,ru,rh,pd,ag,cd,in,sn,sb,te,i,xe,cs,ba,la,ce,pr,nd,pm,sm,eu,gd,tb,dy,ho,er,tm,yb,lu,hf,ta,w,re,os,ir,pt,au,hg,tl,pb,bi,po,at,rn,fr,ra,ac,th,pa,u,np,pu,am,cm,bk,cf,es,fm,md,no,lr,rf,db,sg,bh,hs,mt,ds,rg,cn,uut,fl,uup,lv,uus,uuo'.split(',')[e]for e in i])

Input: A list or a string of integers from 1 to 118.

Usage: i=[9,53,75,0,53,16,0,9,92,7]

Output: The words for each chemical element if possible. Otherwise return False, throw an error, or blank. Note in your program 0 must return a whitespace or newline. Ignore all integers not in range.

PS: used 2.x for the print statement without parenthesis

JavaScript (ES6), 347 279 bytes
l=>l.map(n=>" HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".match(/[ A-Z][a-z]*/g)[n]||"").join``

Explanation
Uses @CSᵠ's idea of seperating the element names by capital letters. Converting the output to all upper or lower case would add 14 bytes.
l=>
  l.map(n=>                   // iterate through each number

    " HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo"
      .match(/[ A-Z][a-z]*/g) // split the elements by the first letter being upper-case

        [n]                   // add the element name to the output
          ||""                // add nothing if the number was out of range
  ).join``                    // return the output as a string

Test

<input type="text" id="input" value="9 53 75 0 53 16 0 9 92 7" /><button onclick='result.innerHTML=(

l=>l.map(n=>" HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".match(/[ A-Z][a-z]*/g)[n]||"").join``

)(input.value.split(" "))'>Go</button>

ES6, 396 bytes
A very trivial approach:
var C=c=>c.map(a=>(" .h.he.li.be.b.c.n.o.f.ne.na.mg.al.si.p.s.cl.ar.k.ca.sc.ti.v.cr.mn.fe.co.ni.cu.zn.ga.ge.as.se.br.kr.rb.sr.y.zr.nb.mo.tc.ru.rh.pd.ag.cd.in.sn.sb.te.i.xe.cs.ba.la.ce.pr.nd.pm.sm.eu.gd.tb.dy.ho.er.tm.yb.lu.hf.ta.w.re.os.ir.pt.au.hg.tl.pb.bi.po.at.rn.fr.ra.ac.th.pa.u.np.pu.am.cm.bk.cf.es.fm.md.no.lr.rf.db.sg.bh.hs.mt.ds.rg.cn.uut.fl.uup.lv.uus.uuo").split(".")[a]||"").join("");

Test it

no need for the var prefix and semicolon ; at the end in codegolf. insta 5 bytes off

Java, 470 bytes
interface B{static void main(String[]a){for(int i=0;i<a.length;i++)System.out.print(" ,h,he,li,be,b,c,n,o,f,ne,na,mg,al,si,p,s,cl,ar,k,ca,sc,ti,v,cr,mn,fe,co,ni,cu,zn,ga,ge,as,se,br,kr,rb,sr,y,zr,nb,mo,tc,ru,rh,pd,ag,cd,in,sn,sb,te,i,xe,cs,ba,la,ce,pr,nd,pm,sm,eu,gd,tb,dy,ho,er,tm,yb,lu,hf,ta,w,re,os,ir,pt,au,hg,tl,pb,bi,po,at,rn,fr,ra,ac,th,pa,u,np,pu,am,cm,bk,cf,es,fm,md,no,lr,rf,db,sg,bh,hs,mt,ds,rg,cn,uut,fl,uup,lv,uus,uuo".split(",")[Integer.parseInt(a[i])]);}}
Accepts input as command line arguments. Uses an interface declaration to shorten class/main declaration. It will definitely error for invalid input. Because Java.

Ruby, 282
->a{a.each{|n|" HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".bytes{|j|n-=1-j/96;n==-1&&$><<j.chr}}}

Ungolfed in test program
Each number in turn is assigned to n. We run through the magic string bytewise, decreasing n unless the ASCII code is more than 96. When n is -1 we print a byte from the magic string. As n remains the same until all characters for that element are printed, all characters for that element are printed. Out of range numbers are simply ignored.
f=->a{
  a.each{|n|
    " HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".
    bytes{|j|n-=1-j/96;n==-1&&print(j.chr)}
  }
}

f[[59,8,24,95,49,0,15,92,40,99,0,95,60,0,27,4,0,27,53,9]]

Output
PrOCrAmIn PUZrEs AmNd CoBe CoIF

Mixed case. All lowercase would cost an extra 9. All uppercase would cost an extra 7.

JavaScript, 275 273 272 bytes
a=>a.map(b=>" HHeLiBeBCNOFNeNaMgAlSiPSClArKaCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo".split(/(?=[A-Z])/)[b]).join``

You can try it here : JSFiddle

shave a byte by removing the /g flag, no need when splitting