text:
Divide a number by 3 without using *, /, +, -, % operators
Quoting this question on SO (Spoiler alert!):

This question has been asked in an Oracle interview.
How would you divide a number by 3 without using *, /, +, -, %,
  operators?
The number may be signed or unsigned.

The task is solvable, but see if you can write the shortest code.
Rules:

Perform the required integer division (/3)
Do not use the non-text-based operators *, /, +, -, or % (or their equivalents, such as __div__ or add()). This also applies to incrementing and decrementing operators, like i++ or i--. Use of operators for string concatenation and formatting are OK. Using these characters for different operators, such as unary - operator for negative numbers, or * to represent a pointer in C is OK as well.
Input value can be arbitrarily large (whatever your system can handle), both positive and negative
Input can be on STDIN or ARGV or entered any other way
Create the shortest code you can to do the above

How should the result be rounded when positive? How when negative?

J, 45 44  10 chars
".,&'r3'":
Works with negatives:
".,&'r3'": 15
5
   ".,&'r3'": _9
_3
   ".,&'r3'": 3e99
1e99

": - format as text
,&'r3' - append r3 to the end
". - execute the string, e.g. 15r3

what is the '%' operator in J mean?  same with '+', '/'?

@acolyte Thanks for reminding.. I think I've fixed code now. -. is matrix subtraction - is this allowed?

i have no idea haha.

I don't think this qualifies because of the % and +. The % you can replace by using 0.333333 but you'll still have the problem of your addition. Possibly though you could look into the Base and Antibase (#:, #.) operators to reproduce the method you use in your Ruby solution?

@Gareth Sorry, wrong rollback it was.

Ah, I see. Clever. I think you're probably ok with the -. for removing values from the set.

@Gareth #: is #. behaves strangely to me, I can't understand the logic. I mean with base 2 it works clear, but base 3.. 3 #. 1 0 0 -> 9 -- ok, but.. 3 #: 9 -> 0 -- why?

It works if you do 3 3 3 #: 9. It looks like you need to know how long your ternary number will be. _3]\i. is also a possible starting point for something, but I don't know if it would be shorter than your solution here. The problem with #_3]\i. as it stands is that it always rounds up instead of down.

Maybe ##~3=_3#\i. for 11 characters?

Actually, you can shrink yours down to 10 characters with ##~0 0 1$~.

@Gareth nice one!

@Gareth I've come up with almost direct translation from Ruby version 3 :'3#.}:(($&3)y)#:y' but it doesn't handle negative values unlike Ruby version.

You can shrink that down using a hook to 3#.}:(#:~$&3) but it's still longer and it doesn't fix the negative number issue.

@Gareth updated, now works for negs. But is there a shorter form of flow control in J? Of course I can use *&y*t to determine the sign of the y and multiply but it's against the rules

Yes, you can use either the Power function ^: or Agenda @. for an if or if...else replacement. In this case you might be able to use @. with two verbs connected with a '`' character (a gerund in J-speak) to select one or the other based on a condition.

You can turn it into 2 lines like this: t=.[:#[:#~0 0 1$~] t\([:-[:t|)@.(0>])` for 36 characters (37 including the newline). You may be able to make it shorter using `3 :'...'`.

(]\(0-])@.(0>[)#@(#~0 0 1$~|))` for 30 characters.

@Gareth I haven't catch the @. thing completely yet, but I used (condition){(v1,v2) instead. We've beat my ruby solution by 1 char, hehe

On the other hand we can't use - here, so I replaced it with <:^:(n)0

Nice, never considered using {.

how is this supposed to work? like compile or something? somebody help please. Thanks

+Chui you just enter this line in the j console (repl)

Using J's rational 1/3 with an eval is dangerously close to just using %3 -- imo it's a technicality to say it's not using division directly...

C, 167503724710
Here's my solution to the problem. I admit it is unlikely to win a strict code golf competition, but it doesn't use any tricks to indirectly call built-in division functionality, it is written in portable C (as the original Stack Overflow question asked for), it works perfectly for negative numbers, and the code is exceptionally clear and explicit.
My program is the output of the following script:
#!/usr/bin/env python3
import sys

# 71
sys.stdout.write('''#include <stdint.h>
#include <stdio.h>
int32_t div_by_3(int32_t input){''')

# 39 * 2**32
for i in range(-2**31, 2**31):
    # 18 + 11 + 10 = 39
    sys.stdout.write('if(input==%11d)return%10d;' % (i, i / 3))

# 95
sys.stdout.write(r'''return 7;}int main(int c,char**v){int32_t n=atoi(a[1]);printf("%d / 3 = %d\n",n, div_by_3(n));}''')

Character count: 71 + 39 * 2**32 + 95 = 167503724710
Benchmarks
It was asked how long this would take and how much memory it would use, so here are some benchmarks:

Script execution time — Running ./test.py | pv --buffer-size=1M --average-rate > /dev/null for about 30 seconds gives a rate of about 14.8 MB/s. The rate of output can reasonably be assumed to be roughly constant, so the running time to completion should be about 167503724710 B / (14.8 * 1048576 B/s) ≈ 10794 s.
Compilation time — The TCC compiler claims to compile C code at 29.6 MB/s, which makes for a compilation time of 167503724710 B / (29.6 * 1048576 B/s) ≈ 5397 s. (Of course this can run in a pipeline with the script.)
Size of compiled code — I tried estimating it using ./test.py | tcc -c - -o /dev/stdout | pv --buffer-size=1M --average-rate > /dev/null, but it seems tcc doesn't output anything until it reads the entire source file in.
Memory usage to run — Since the algorithm is linear (and tcc doesn't optimize across lines), the memory overhead should be only a few kilobytes (apart from the code itself, of course).

This is the epitome of hardcoding. ++++++++++

That being said, I'm sure if you gave them a 160 GB source file and asked them to compile and test it, they'd look at you like you were crazy.

If my boss asked me to compute a division by three without - + / * % I would think he's crazy.

And yet, a[b] is a syntactic sugar for *(a + b), which does the addition.

You did not give an answer. You say that your answer is the output of a program. So you should give the output, not the program.

@NicolasBarbulesco There is a size restriction on Stack Exchange answers.

How about outputting the assembly?

You can speed it up by hardcoding binary search using a tree of nested ifs, with bitwise & to optimize the comparison against a power of two.

Ruby 28
b=->n{n.to_s(3).chop.to_i 3}

To divide by 3 we just need to remove the trailing zero in base 3 number:
120 -> 11110 -> 1111 -> 40
Works with negatives:
ice distantstar:~/virt/golf [349:1]% ruby ./div3.rb
666
222
ice distantstar:~/virt/golf [349]% ruby ./div3.rb
-15
-5

Ruby, 6045
Alternatively, w/o using base conversion:

    d=->n{x=n.abs;r=(0..1.0/0).step(3).take(x).index x;n>0?r:-r}

d=->n{(r=1.step(n.abs,3).to_a.size);n>0?r:-r}

The alternate without base conversion has the banned / operator where Float::INFINITY became 1.0/0. With Ruby 2.1, one may golf (0..1.0/0).step(3) into 0.step(p,3), removing the /. The bigger problem is that -r uses - to negate. It costs 5 characters to change -r to ~r.pred, abusing Integer#pred to subtract 1 without the subtraction operator.

Mathematica, 13 chars
Mean@{#,0,0}&

This is wicked :D  I guess you could save the & and use a plain variable (others here do that too).

@YvesKlett: Mean is inherently wicked.

JavaScript, 56
alert(Array(-~prompt()).join().replace(/,,,/g,1).length)

Makes a string of length n of repeating ,s and replaces ,,, with 1. Then, it measures the string's resulting length. (Hopefully unary - is allowed!)

+1 but it doesn't work with negative values

Uh, question... how does this count? It uses the - negation operator.

@Patrick I took the specification to mean no subtraction -- if you want, you can replace -~ with parseInt()

@CaseyChu the value returned by -~prompt() is one greater than parseInt(prompt()). Not sure how you'd deal with that.

alert(Array(parseInt(prompt())).slice(1).join().replace(/,,,/g,1).length)

@CaseyChu, I said one greater, not one less.

You could do alert((Array(parseInt(prompt()))+",").replace(/,,,/g,1).length).

@ETHproductions then you are using the also blacklisted + operator

@ShaunH + is allowed for string concatenation.

Instead of using alert, you can use f=>Rest Of Code, as an anonymous function

Python, 41 38
print"-"[x:]+`len(xrange(2,abs(x),3))`

xrange seems to be able to handle large numbers (I think the limit is the same as for a long in C) almost instantly.
>>> x = -72
-24

>>> x = 9223372036854775806
3074457345618258602

10/3 equals 3, not 4.

Doing print" -"[x<0]+len(range(2,abs(x),3))`` will shave it down to 39 chars

golfexchange's comment formatting is messing it up. on the above I used backticks to enclose len() as shorthand for repr()

I've updated it. I can't use range, because it will actually create the list. xrange just pretends to, so it is able to handle huge numbers without wasting time/memory.

Pretend it's Python 3 ;) I like the single char slicing btw.

Haskell, 90 106
d n=snd.head.dropWhile((/=n).fst)$zip([0..]>>=ν)([0..]>>=replicate 3>>=ν);ν q=[negate q,q]

Creates an infinite (lazy) lookup list [(0,0),(0,0),(-1,0),(1,0),(-2,0),(2,0),(-3,-1),(3,1), ...], trims all elements that don't match n (/= is inequality in Haskell) and returns the first which does.
This gets much simpler if there are no negative numbers:
25 27
(([0..]>>=replicate 3)!!)

simply returns the nth element of the list [0,0,0,1,1,1,2, ...].

o.O  i never thought of that second solution.  I might be able to implement something like that in python

C#,  232 bytes
My first code golf... And since there wasn't any C# and I wanted to try a different method not tried here, thought I would give it a shot. Like some others here, only non-negative numbers.
class l:System.Collections.Generic.List<int>{}class p{static void Main(string[] g){int n=int.Parse(g[0]);l b,a=new l();b=new l();while(a.Count<n)a.Add(1);while(a.Count>2){a.RemoveRange(0,3);b.Add(1);}System.Console.Write(b.Count);}}

Ungolfed
class l : System.Collections.Generic.List<int>
{ }
class p
{
    static void Main(string[] g)
    {
        int n = int.Parse(g[0]);
        l b, a = new l();
        b = new l();
        while (a.Count < n) a.Add(1);
        while (a.Count > 2)
        {
            a.RemoveRange(0, 3);
            b.Add(1);
        }
        System.Console.Write(b.Count);
    }
}

About 5 years later.. You can save 1 byte by removing the space from string[] g, turning it into string[]g

Quoting "Do not use the non-text-based operators *, /, +, -, or % (or their equivalents, such as div or add()" -- are you not using an equivalent -- .Add?

@JonathanFrech That add method does not work on two numbers, it only adds a value to a collection

Perl (26 22)
$_=3x pop;say s|333||g

This version (ab)uses Perl's regex engine. It reads a number as the last command line argument (pop) and builds a string of 3s of this length ("3" x $number). The regex substitution operator (s///, here written with different delimitiers because of the puzzle's rules and with a global flag) substitues three characters by the empty string and returns the number of substitutions, which is the input number integer-divided by three. It could even be written without 3, but the above version looks funnier.
$ perl -E '$_=3x pop;say s|333||g' 42
14

Hey @memowe, nice work! You could save a few more chars (4) by doing $_=3x pop;say s|333||g.

When the input is 0, 1, or 2, then it prints an empty string. If it needs to print 0, then it needs 3 more characters (25 total): '$_=3x pop;say s|333||g||0. Slow with large numbers like 99999999, and doesn't work with negative numbers.

Use -p on the commandline, and you can do: $_=3x$_;$_=0|s|...||g for a total of 22, including coverage of the 0, 1, or 2 inputs.

JavaScript, 55
alert(parseInt((~~prompt()).toString(3).slice(0,-1),3))

If one can't use -1, then here is a version replacing it with ~0 (thanks Peter Taylor!).
alert(parseInt((~~prompt()).toString(3).slice(0,~0),3))

What does ~~ mean in javascript?

@ArtemIce One ~ is a Bitwise operator which inverts the bits of the operand (first converting it to a number). This is the shortest way to convert a string to a number (as far as I know).

I feel like using string parsing/conversion is cheating, since its a) a very complicated and expensive process compared to bitwise operations, b) uses the forbidden operators internally, and c) would take up waaaaay more characters than a homerolled solution.  Kind of like how people get grumpy when you use the built in sorts when asked to implement a quicksort.

@Inkbug, I think you can also use the unary + operator as a slightly shorter way to coerce a string into a number.

@Sam While "text-based" + is allowed, I'm not sure that using it to convert a string to a number is allowed.

@Sam Also, ~~ converts to an integer, as opposed to +.

@Wug It is codegolf, thus it's not about efficiency unless specified in the task.

@ArtemIce If someone rolled their own string parser to do it that would be fine, but there's no challenge if you just use the languages build in parsing.  This is the point I was trying to make with the sorting analogy.

@Inkbug, yes, now I can see why you used ~~. I should have paid more attention before commenting.

+1 for taking advantage of different bases. It's one of my favorite JavaScript golf techniques.

Bravo! This deserves more upvotes! It works with positive and negative.

Python 42
int(' -'[x<0]+str(len(range(2,abs(x),3))))

Since every solution posted here that Ive checked truncates decimals here is my solution that does that.
Python 50 51
int(' -'[x<0]+str(len(range([2,0][x<0],abs(x),3))))

Since python does floor division, here is my solution that implements that.
Input integer is in the variable x.
Tested in Python 2.7 but I suspect it works in 3 as well.

+1 For offering both alternatives to the negative value situation. Since there are already so many answers, I'll not be adjusting the spec to exclude one or the other option, though I would personally agree that -3 is the correct answer to -10/3.

For those who care about floor division in python:
http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html

what's with the multiplication and subtraction in your second solution?

@boothby The second solution implements floor division. I wanted to do range(0,abs(x),3) for negative numbers and range(2,abs(x),3) for positive numbers. In order to do that I had range(2... then i subtracted 2 when x is negative. X<0 is True when x is negative, (True)*2 == 2

I'm not understanding the difference between floor division and truncating decimals. Does this have to with negative division?

@JoelCornett Yes, if your division truncates decimals the result is the same as float division, then you round toward zero. Floor division is when your result is the same as float division, but then you round down. For positive results these are the same, for negative results they are not.

@Matt, print starts with pr and the challenge says not to use +-/*.

@boothby yes, print does start with pr, but I do not believe that the challenge required us to print the result, it just said we should calculate it. You are right about +-/* though, I forgot about that temporarily. I shall have to revise that answer.

C, 160 chars
Character by character long division solution using lookup tables, i.e. without string atoi() or printf() to convert between base 10 strings and integers.
Output will sometimes include a leading zero - part of it's charm.
main(int n,char**a){
char*s=a[1],*x=0;
if(*s==45)s=&s[1];
for(;*s;s=&s[1])n=&x[*s&15],x="036"[(int)x],*s=&x["000111222333"[n]&3],x="012012012012"[n]&3;
puts(a[1]);
}

Note:

abuses array access to implement addition.
compiles with clang 4.0, other compilers may barf.

Testing:
./a.out -6            -2
./a.out -5            -1
./a.out -4            -1
./a.out -3            -1
./a.out -2            -0
./a.out -1            -0
./a.out 0             0
./a.out 1             0
./a.out 2             0
./a.out 3             1
./a.out 4             1
./a.out 5             1
./a.out 6             2
./a.out 42            14
./a.out 2011          0670

C 83 characters
The number to divide is passed in through stdin, and it returns it as the exit code from main() (%ERRORLEVEL% in CMD). This code abuses some versions of MinGW in that when optimizations aren't on, it treats the last assignment value as a return statement. It can probably be reduced a bit. Supports all numbers that can fit in to an int
If unary negate (-) is not permitted: (129)
I(unsigned a){a=a&1?I(a>>1)<<1:a|1;}main(a,b,c){scanf("%i",&b);a=b;a=a<0?a:I(~a);for(c=0;a<~1;a=I(I(I(a))))c=I(c);b=b<0?I(~c):c;}

If unary negate IS permitted: (123)
I(unsigned a){a=a&1?I(a>>1)<<1:a|1;}main(a,b,c){scanf("%i",&b);a=b;a=a<0?a:-a;for(c=0;a<~1;a=I(I(I(a))))c=I(c);b=b<0?-c:c;}

EDIT: ugoren pointed out to me that -~ is an increment...
83 Characters if unary negate is permitted :D
main(a,b,c){scanf("%i",&b);a=b;a=a<0?a:-a;for(c=0;a<~1;a=-~-~-~a)c=-~c;b=b<0?-c:c;}

If unary negate is permitted, x+3 is -~-~-~x.

Thank you for that. I don't know why that never occurred to me. I guess I didn't realize you could stack unaries so gratuitously hehe.

C, 139 chars
t;A(a,b){return a?A((a&b)<<1,a^b):b;}main(int n,char**a){n=atoi(a[1]);for(n=A(n,n<0?2:1);n&~3;t=A(n>>2,t),n=A(n>>2,n&3));printf("%d\n",t);}

Run with number as command line argument

Handles both negative and positive numbers

Testing:
 ./a.out -6            -2
 ./a.out -5            -1
 ./a.out -4            -1
 ./a.out -3            -1
 ./a.out -2            0
 ./a.out -1            0
 ./a.out 0             0
 ./a.out 1             0
 ./a.out 2             0
 ./a.out 3             1
 ./a.out 4             1
 ./a.out 5             1
 ./a.out 6             2
 ./a.out 42            14
 ./a.out 2011          670

Edits:

saved 10 chars by shuffling addition (A) to remove local variables.

Nicely done. I tried my best at bit twiddling and got to 239. I just can't get my head around your A, my function just checks the bit i in number n. Does C standard allow omitting type declarations or is that some compiler thing?

C will assume int if unspecified.

C, 81 73 chars
Supports non-negative numbers only.
char*x,*i;
main(){
    for(scanf("%d",&x);x>2;x=&x[~2])i=&i[1];
    printf("%d",i);
}

The idea is to use pointer arithemtic. The number is read into the pointer x, which doesn't point anywhere. &x[~2] = &x[-3] = x-3 is used to subtract 3. This is repeated as long as the number is above 2. i counts the number of times this is done (&i[1] = i+1).

Trying to understand the code,somebody shed some lights? Thanks

@Chui, added explanation.

@ugoren as far as I understand, shouldn't printf("%d") print out the memory address pointer i holds in Hex? why it is printing out an integer? or char* i was initialized to point to memory address 0 by default? Thanks

ZSH — 31 20/21
echo {2..x..3}|wc -w

For negative numbers:
echo {-2..x..3}|wc -w

With negative numbers (ZSH + bc) — 62 61
I probably shouldn't give two programs as my answer, so here's one that works for any sign of number:
echo 'obase=10;ibase=3;'`echo 'obase=3;x'|bc|sed 's/.$//'`|bc

This uses the same base conversion trick as Artem Ice's answer.

Java 86 79
Assume the integer is in y:
Converts to a string in base 3,
removes the last character ( right shift ">>" in base 3 ),
then converts back to integer.
Works for negative numbers.
If the number, y, is < 3 or > -3, then it gives 0.
System.out.print(~2<y&y<3?0:Long.valueOf(Long.toString(y,3).split(".$")[0],3));

First time posting on code golf. =) So can't comment yet.
Thx Kevin Cruijssen for the tips.

I know it's been more than two years ago, but you can golf a few parts: && to &, and 2x Integer to Long. (Also, why do you use ~2 instead of just -3? They are the same byte-count.)

@KevinCruijssen So nostalgic to edit my first post after so long. Wasn't too sure why I thought ~2 was better back then.

@KevinCruijssen well, the challenge says you're not allowed to use -, but I don't know if that counts for unary negation.

@FlipTack Ah you're completely right. In that case forget I ever said it. :)

Javascript, 47 29
Uses eval to dynamically generate a /. Uses + only for string concatenation, not addition.
alert(eval(prompt()+"\57"+3))

EDIT: Used "\57" instead of String.fromCharCode(47)

-1 for alert(eval(prompt()+"\573"))?

Ruby (43 22 17)
Not only golf, but elegance also :)
p Rational gets,3

Output will be like (41/1). If it must be integer then we must add .to_i to result, and if we change to_i to to_f then we will can get output for floats also.

Works without the require rational line on Ruby 1.9.3. Omitting the parentheses saves one more char.

Python2.6 (29)(71)(57)(52)(43)
z=len(range(2,abs(x),3))
print (z,-z)[x<0]

print len(range(2,input(),3))

Edit - Just realized that we have to handle negative integers too. Will fix that later
Edit2 - Fixed
Edit3 - Saved 5 chars by following Joel Cornett's advice
Edit4 - Since input doesn't have to be necessarily be from STDIN or ARGV, saved 9 chars by not taking any input from stdin

Go ahead with abs()

shorter to do print z if x==abs(x) else -z

better yet, print (z,-z)[x<0]

@ArtemIce thanks, only realized I could use that after reading another answer above.

@JoelCornett humm, didn't know about that, thanks

TI-Basic, 8 bytes
Winner? :)
int(mean({Ans,0,0

P.S. Rounds towards infinity for negative numbers (see here for why). To round to zero instead, replace int( with iPart( for no byte change.
Test cases
-4:prgmDIVIDE
              -2
11:prgmDIVIDE
               3
109:prgmDIVIDE
              36

 Python 2.x, 54 53 51
print' -'[x<0],len(range(*(2,-2,x,x,3,-3)[x<0::2]))
Where _ is the dividend and is entered as such.
>>> x=-19
>>> print' -'[x<0],len(range(*(2,-2,x,x,3,-3)[x<0::2]))
- 6

Note: Not sure if using the interactive interpreter is allowed, but according to the OP: "Input can be on STDIN or ARGV or entered any other way"
Edit: Now for python 3 (works in 2.x, but prints a tuple). Works with negatives.

Works in python 3 as well?

Doesn't have to be subscriptable; having __len__ is enough.

len(range(100,1000)) gives 900 in 3.2.3 on linux.

This doesn't work for negative numbers. And len(xrange(0,_,3)) is shorter and massively faster anyway.

@Mechanicalsnail: Point taken. I concede. It does work on 3.

@grc: Edited based on your comment. Still working on the negative number thing.

Golfscript - 13 chars
~3base);3base

doesn't seem to handle negative input

@r.e.s. s/seem to // :(. I'll have to have a think about it

PowerShell 57 or 46
In 57 characters using % as the PowerShell foreach operator, not modulo. This solution can accept positive or negative integers.
(-join(1..(Read-Host)|%{1})-replace111,0-replace1).Length

In 46 characters if * is allowed as the string repetition operator, not multiply. This option requires positive integers as input values.
("1"*(Read-Host)-replace111,0-replace1).Length

If you ever come back, I posted a bug fix. If you want me to delete mine and incorporate the change into yours, just let me know.

C++, 191
With main and includes, its 246, without main and includes, it's only 178.  Newlines count as 1 character.  Treats all numbers as unsigned.  I don't get warnings for having main return an unsigned int so its fair game.
My first ever codegolf submission.
#include<iostream>
#define R return
typedef unsigned int U;U a(U x,U y){R y?a(x^y,(x|y^x^y)<<1):x;}U d(U i){if(i==3)R 1;U t=i&3,r=i>>=2;t=a(t,i&3);while(i>>=2)t=a(t,i&3),r=a(r,i);R r&&t?a(r,d(t)):0;}U main(){U i;std::cin>>i,std::cout<<d(i);R 0;}

uses shifts to divide number by 4 repeatedly, and calculates sum (which converges to 1/3)
Pseudocode:
// typedefs and #defines for brevity

function a(x, y):
    magically add x and y using recursion and bitwise things
    return x+y.

function d(x):
    if x = 3:
        return 1.
    variable total, remainder
    until x is zero:
        remainder = x mod 4
        x = x / 4
        total = total + x
    if total and remainder both zero:
        return 0.
    else:
        return a(total, d(remainder)).

As an aside, I could eliminate the main method by naming d main and making it take a char ** and using the programs return value as the output.  It will return the number of command line arguments divided by three, rounded down.  This brings its length to the advertised 191:
#define R return
typedef unsigned int U;U a(U x,U y){R y?a(x^y,(x|y^x^y)<<1):x;}U main(U i,char**q){if(i==3)R 1;U t=i&3,r=i>>=2;t=a(t,i&3);while(i>>=2)t=a(t,i&3),r=a(r,i);R r&&t?a(r,d(t)):0;}

R
These only work with positive integers:
max(sapply(split(1:x,1:3), length))
# Gives a warning that should be ignored

Or:
min(table(rep(1:3, x)[1:x]))

Or:
length((1:x)[seq(3,x,3)])

Or:
sum(rep(1,x)[seq(3,x,3)])

[[EDIT]] And an ugly one:
trunc(sum(rep(0.3333333333, x)))

[[EDIT2]] Plus probably the best one - inspired by the matlab code above by Elliot G:
length(seq(1,x,3))

I wanted to implement the same idea as in your EDIT2 but it does not work for negative numbers: wrong sign in 'by' argument

SmileBASIC, 58 51 36 bytes (no mathematical functions!)
INPUT N
BGANIM.,4,-3,N
WAIT?BGROT(0)

Explanation:
INPUT N           'get input
BGANIM 0,"R",-3,N 'smoothly rotate background layer 0 by N degrees over 3 frames
WAIT              'wait 1 frame
PRINT BGROT(0)    'display angle of layer 0

The program moves the background layer smoothly over 3 frames, and then gets the angle after 1 frame, when it has traveled 1/3 of its total distance.
Float division version, 38 bytes:
INPUT N
BGANIM.,7,-3,N
WAIT?BGVAR(0,7)

Explanation:
INPUT N           'input
BGANIM 0,"V",-3,N 'smoothly change layer 0's internal variable to N over 3 frames
WAIT              'wait 1 frame
PRINT BGVAR(0,7)  'display layer 0's internal variable

Haskell 41 39 chars
Works with the full set of positive and negative integers
f n=sum[sum$1:[-2|n<0]|i<-[3,6..abs n]]

First creates a list 1's or (-1)'s (depending on the sign of the input) for every third integer from 0 up until the input n. abs(n) for negative numbers inclusive.
e.g n=8 -> [0,3,6]
It then returns the sum of this list.

Doesn't work on negative numbers (-3/3 is -1 not 1).

Nice you made it work on negative numbers but you can't use /, read the specification.

Oh gosh, you got me twice. All fixed ;)

Nice! Btw You can get 39 chars with
f n=sum[sum$1:[-2|n<0]|i<-[3,6..abs n]]

Python 3, 72 bytes
f=lambda x:x and s(x>>1,f(x>>1))
s=lambda x,y:y and s(x^y,(~x&y)<<1)or x

Try it online!
A bitwise solution consisting of two recursive functions, one to calculate third, the other to subtract. Because multiplying and dividing by 2 is easy to do bitwise, we can use the fact:
\$X/3=X/2-(X/2)/3\$
to recursively find the third.
It does produce some weird rounding patterns for non-multiples of three.
0 -> 0 (0)
1 -> 0 (0.333...)
2 -> 1 (0.666...)
3 -> 1 (1)
4 -> 1 (1.333...)
5 -> 1 (1.666...)
6 -> 2 (2)
7 -> 2 (2.333...)
8 -> 3 (2.666...)
9 -> 3 (3)
10 -> 4 (3.333...)
11 -> 4 (3.666...)
12 -> 4 (4)
13 -> 4 (4.333...)
14 -> 5 (4.666...)
15 -> 5 (5)

Mathematica 36 51 42 chars
This is easily achieved in base 3.
IntegerDigits[n,3] converts the absolute value of the number to base 3.
Most takes all but the rightmost digit. This "rightward shift" amounts to integer division by 3.
FromDigits converts back to base 10.
Sign restores, if necessary, the sign.
Sign@n*Most@IntegerDigits[n,3]~FromDigits~3

Sage Notebook   (21)
ZZ(n.digits(3)[1:],3)

Clojure, 87; works with negatives; based on lazyseqs
(defn d[n](def r(nth(apply interleave(repeat 3(range)))(Math/abs n)))(if(> n 0)r(- r)))

Ungolfed:
(defn d [n]
  (let [r (nth (->> (range) (repeat 3) (apply interleave))
               (Math/abs n))]
        (if (pos? n)
          r
          (- r))))

F# (81)
Using inclusive ranges:
let(^)s x=if s<0 then int("-"+string x)else x
let d m =sign m^[3..3..abs m].Length

Alternatively, using strings:
let (^) s x = if s < 0 then int("-" + string x) else x
let d m =
  let n = abs m
  [0..n]
  |> Seq.map (fun i -> i, String.replicate i "aaa")
  |> Seq.takeWhile (fun (i, s) -> s.Length <= n)
  |> Seq.last
  |> fst
  |> (^) (sign m)

This is verbose but it's better than being forced to use loops in many imperative languages. String.replicate is especially valuable.

This looks like it uses multiplication * to restore the sign bit.

APL (NARS2000), 7 characters
Inspiration
⍎⍞,'r3'

⍎ evaluate
⍞ text input
,'r3' followed by "r3"
So "15" becomes "15r3" which is NARS2000's rational point notation and evaluates to 5.
Note that the OP states

Input can be on STDIN or ARGV or entered any other way
Create the shortest code you can to do the above

which allows me to take input as string, and count code length in characters (not bytes – as this is a fairly old challenge that predates the adoption of bytes as default code length unit).

05AB1E, 5 bytes
3B¨3ö

Try it online!

C# with Linq, 51 Bytes
using System.Linq;(n)=>(int)new[]{n,0,0}.Average();

Unfortunately much longer than the Mathematica version of this approach (pesky using statement), but pretty good for C#.
Try it out here.

C (gcc), 72 69 59 58 bytes
a,q;f(x){for(a=q=0;a=-~-~-~a,a<=abs(x);)q=-~q;x=x<0?-q:q;}

Try it online!
Edit: Now works with negative arguments.

Haskell, 62 52 41 Chars
f n=sum[last$1:[-1|n<0]|i<-[3,6..abs(n)]]

If using sum is not allowed, here's a 52 char solution:
f n|n>0=s|1>0=(-s)where s=length[1|i<-[3,6..abs(n)]]

Scala 96
def d(x:Int)={val y=x.abs;val r=0.to(y).flatMap(List.fill(3)(_)).drop(y).head;if(x==y)r else -r}

I do realize now it is basically the same idea behind some other answers here (Haskell, Clojure and the 2nd take of this one in Ruby, to name a few)... :-/

C++ 633 byes (including whitespace; 457 bytes excluding scaffolding)
I know this is not anywhere near the shortest code, but it does have some "advantages". First the code:
#include <climits>
#include <cstdlib>
#include <iostream>
using namespace std;typedef int I;typedef unsigned U;U A(U l,U r){U t;while(r)t=l^r,r=(l&r)<<1,l=t;return l;}
#define N(l)A(~l,1)
#define S(l,r)A(l,N(r))
U M(U l, U r){U p=0;while(r){if(r&1)p=A(p,l);l<<=1;r>>=1;}return p;}U D(U n,U&r){U m=U(1)<<S(M(sizeof(U),CHAR_BIT),1),q=r=0,x=1;while(x){q<<=1;r<<=1;if(n&m)r|=1;if(r>=3)q|=1,r=S(r,3);n<<=1;x<<=1;}return q;}I D(I n,I&r){bool o=n<0;U p=o?N(n):n,s,t;s=D(p,t);r=o?N(t):t;return o?N(s):s;}I main(I c,char**v){I i=1,q,r;while(i<c)q=D(atoi(v[i]),r),cout<<v[i]<<" divided by 3 == "<<q<<" with a remainder of "<<r<<endl,i=A(i,1);}

The advantages over the other solutions, even though it can't win on a purely codegolf basis:

It only uses the standard library to obtain the value of CHAR_BIT, atoi, cout, and endl. Consequently, it does not depend on any math routines in the standard library beyond those to convert a string to and from a number. It most definitely does not use any part of the standard library to divide by 3.
It at no time uses any of the operators + - * / % (binary or unary, numeric or string). Note that it does use two asterisks to declare a pointer to a pointer to char, but it only uses that to access command line parameters of number to divide.
It uses bit manipulation and relational operators exclusively in the division process.
If the scaffolding code (main and two of the three include files) is removed, the code that does the actual work of division by 3 is only 457 bytes.
I'm pretty sure this code should work on any C++ compiler conforming to the standard and does not exploit any tricks that only work on a subset of compilers or platforms. One possible exception to this is it might not work on a platform that does not use twos complement signed integers, though I don't have access to any platform like that to test that theory. Another possible exception (related) is if automatic signed / unsigned conversions are not supported as they are for most (or all) platforms utilizing twos complement signed integers.

I'm sure there are other ways to make this shorter, but I've spent enough time on it. Mainly I wanted to perform the exercise without any "cheating" via use of any operations from the standard library. By defining functions and macros that perform unary negation, addition, subtraction, multiplication, and division strictly in terms of bit level operations and relational operators, signed (or unsigned) integers can be divided by three. I've hard coded the divisor to 3 to remove a few bytes of code here and there, though adding a parameter to pass in the divisor is fairly trivial.
The signed division function notes the sign of the dividend then calls the unsigned division function with the dividends absolute value. Once the unsigned division returns the unsigned quotient and remainder, the original sign is used to negate the signed quotient and remainder as needed.
Edit: Only after I wrote and submitted my solution did I go look at the original question on SO. Some interesting stuff there, and of course someone had already come up with my solution. FWIW, I did write this on my own! Not that it matters for this old of a question, especially in a codegolf exercise. :)

OCTAVE/MATLAB 13
Code where x is an integer. Only works for positive integers and rounds the result up.
length(1:3:x)

You could replace length with nnz

Java 317
I know this is extremely long, and I know this is supposed to be code golf, but for kicks I wanted to write a version that ALSO:

Doesn't use the characters [0-9]
Doesn't branch

Enjoy :)
import java.util.LinkedList;class Div{int d(int a){int t=getClass().getName().length();char[]s=Integer.toString(a,t).toCharArray();StringBuilder b=new StringBuilder();LinkedList<Character>l=new LinkedList<>();for(char z:s){l.add(z);}l.removeLast();for(char z:l){b.append(z);}return Integer.valueOf(b.toString(),t);}}

Perl 5, 158 characters
sub t{use integer;$m=unpack(J,U x 8)^(($n=pop)>0&&3);$p=0;for($t= ~0;$t;$t<<=1){$c=$p&($o=$m&1&&$n);$p=($p^$o)>>1;($p,$c)=($p^$c,($p&$c)<<1)while$c;$m>>=1}$p}

This is more than 7 times longer than the answer by memowe, but it runs faster when the input is large, and supports negative inputs. Now you can divide -2147483648 by 3. This defines a sub. t(-2147483648) returns -715827883 because it rounds down.
Division is multiplication!
Division by 3 uses the formula

n ÷ 3 = n × (264 ÷ 3) ÷ 264

with an integer constant to approximate 264 ÷ 3. The algorithm multiplies by this constant and drops the lower 64 bits of the 128-bit product. To prevent error, n must be in range for a signed 64-bit integer, and the constant must be

⌊264 ÷ 3⌋ = 5555 5555 5555 555516 if n is negative, or
⌈264 ÷ 3⌉ = 5555 5555 5555 555616 if n is positive.

Multiplication uses an add-and-shift loop. Addition uses bitwise-xor to add and bitwise-and to carry. Shifts preserve the high 64 bits of each 65-bit sum and the final 128-bit product.
Ungolfed code
use strict;
use warnings;

# t($n) is floor($n / 3) with only bitwise operations
sub t {
    use integer; # for signed right shift
    my $n = shift;

    # The formula with 64-bit integers is:
    #   $n / 3 = ($n * (1 << 64) / 3) >> 64
    # If this perl has 32-bit integers, then $m and $t get 32-bit
    # values, so the shifts are by 32.

    # $m = (1 << 64) / 3
    #    = 0x5555 5555 5555 5555 if $n < 0
    #    = 0x5555 5555 5555 5556 else
    my $m = unpack 'J', 'UUUUUUUU';  # Unpack 0x55 bytes.
    $n < 0 or $m ^= 3;               # 0x55 ^ 3 == 0x56

    # Multiplication: $p = ($n * $m) >> 64
    my $p = 0;
    for (my $t = ~0; $t; $t <<= 1) { # Loop 64 times.
    if ($m & 1) {
        # Add and shift: $p = ($p + $n) >> 1
        # Shift early to prevent 65-bit overflow.
        my $c = $p & $n;         # Carry.
        $p = ($p ^ $n) >> 1;     # Add by exclusive-or.
        while ($c) {
        ($p, $c) = ($p ^ $c, ($p & $c) << 1);
        }
    }
    else {
        $p >>= 1;
    }
    $m >>= 1;
    }
    return $p;
}

# test program: divide integers
use POSIX qw(floor);
for my $integer (@ARGV) {
    $integer = int($integer);
    my $have = t($integer);
    my $want = floor($integer / 3);
    printf("%d -> %d (%s)\n", $integer, $have,
       $have == $want ? "correct" : "OFF BY @{[$want - $have]}");
}

The golfed version has some differences:

It clobbers global variables.
It uses the other value of $m if $n is zero.
It replaces the check if ($m & 1) with a new variable $o=$m&1&&$n.

Julia - 29 characters
I'm assuming n as a variable assigned prior to running this line of code.
parseint(chop(base(3,n,2)),3)

Performs the truncation variant (-35 -> -11 not -12). In the current stable release (0.2.1), this approach only works up to base 36 (for division by 36) as parseint only works for alphanumeric text, but in the 0.3 prerelease (based on the forio.com online REPL), it will work up to 62.
Note that the ",2" at the end is necessary to handle numbers less than 3 (or equivalent) in magnitude, as otherwise chop(base(3,n)) will result in either an empty string (for non-negative values) or "-" (for negative values).

Jelly, 5 bytes
b3Ṗḅ3

Try it online!
Explanation:
 b3Ṗḅ3 Main link. Arguments: z
⁸      (implicit) z
  3    3
 b     Convert x to base y
   Ṗ   Trim last element off x
     3 3
    ḅ  Convert x from base y

APL, 11
3⊥¯1↓3⊥⍣¯1⊢656
218

I'm converting to base 3 and back, removing the last number in the process.
Try it on tryapl.org

Python 3, 31 38 29 chars
print(eval(input()+"%c3"%47))

Edited to add a print statement.
Edited to avoid use of int call.
Kind of cheating. Eval will evaluate and return any operations passed as a string as if it were code. chr() converts an int to the character with that ASCII value, and 47=/. Pass in the / with standard string formatting.

This looks great! It's not cheating.

This is invalid as it is for the lack of print statement, sorry. Simple fix though, just add a print statement. Also, you can make it python2 and skip the 'int()' part.

I only say 'cheating' because it does actually use the division operator, it's just a bit hidden.

Clojure, 74 57 bytes
Improved upon an earlier answer, I'm not sure if I should post this as my own answer or just comment on the original. But this is significantly different way of generating the sequence [0 0 0 1 1 1 2 2 2 ...].
#(let[r(nth(flatten(for[i(range)][i i i]))(Math/abs %))](if(> % 0)r(- r)))

Edit after 1.5 years :D
#((if(> % 0)+ -)(nth(for[i(range)j[i i i]]j)(max(- %)%)))

Aceto, 6 bytes
ri3:ip

r grabs input
i converts to integer
3 pushes 3 on the stack
: does float division
i converts to integer
p prints it
Try it online!

R, 19 bytes
mean(c(scan(),0,0))

Try it online!
Saw this method above in another language, and easily implemented it in R. And it gives precise answers. Works for positive and negative inputs.
R, 18 bytes
gl(x<-scan(),3)[x]

Slightly shorter solution that only works for positive numbers and performs "actual" integer division.
Try it online!

Perl 6, 19 bytes
{Rat.new($_,3).Int}

A rational number in Perl 6 is literally defined as a numerator over a denominator.  So passing it 7 creates the fraction 7/3 .  That fraction is then coerced to an Int.  This should work for all ℤ .
Try it online!

PowerShell, 82 74 bytes
-8 bytes thanks to mazzy

param($n)'-'[$n-ge0]+(-join(0..$n|?{$_}|%{1})-replace111,0-replace1|% Le*)

Try it online!
Bug-fix of Joseph Alcorn's answer to handle negatives correctly.
83 bytes to have 0 instead of -0

-0 is not very nice. Powershell knows how to make ranges with with negative bounds :)

@mazzy If you go 1..$n with a negative, you get two extra iterations. 0..$n is an extra tick as well because you can't do 0..--$n(but can probably be fixed with minimal fuss)

74 bytes :)

is This also applies to incrementing and decrementing operators means Do not use incrementing and decrementing operators? Ok. Then your approach is best.

@mazzy Yep, those are not to be used.

32 characters in Burlesque:
0\/r@{1\/.-<-2\/.-<-}{L[1.>}w!-]

assuming the number to divide is already on the stack. (see here in action).
How does it work? It generates a list of numbers 0..n and then removes one from the left and two from the right until only one number is left. Of course this method only works with numbers that are divisible by 3.

Perl using an eval to compute a string version of x/3.
Perl 5.8 Version
print eval join' ','int',$ARGV[0],map{chr}47,51

Perl 5.10 Version
say print eval join' ','int',$ARGV[0],map{chr}47,51

I'm not sure if the exactly meets the criteria of "without using the / operator". It still uses it, it's just hidden in the code as character 47.

You are correct, this just hides it.
Either way, my solution isn't nearly as good as memowe's version using regular expressions.

perl 23
$_=()=(1x$_)=~/(111)/g

usage:
> echo 1e4|perl -pe'$_=()=(1x$_)=~/(111)/g'
3333

Doesn't work with negatives.

Mathematica (assorted)
Dividing 9 by 3 (but should work for arbitray input). The second version outputs just the number, while the first will offer additional braces (not sure about what is deemed correct, pick your count):
9Inverse[{{3}}]              (*15*)
9Inverse[{{3}}][[1,1]]       (*22*)

LinearSolve[{{3}},{9}]       (*22*)
LinearSolve[{{3}},{9}][[1]]  (*27*)

Python 2, 16 bytes (Joke Answer)
print input()//3

// is not the same as /, the division operator. //, a token in and of itself, is the floor-division operator. Example: 4.5 // 2 == 2. Note that this answer exploits a loophole in the question, and can be considered a joke. However, it is within the technical rules because the question says you cannot use the / operator. Although this answer uses the character "/", it never uses it as an operator.

Hexagony, 28 (Non-competing, only unsigned)
?$\<@'\.|!"1.(|{'&.{&.1\()\$

Try It Online!
Haven't got any Bitwise operators, so either can't join (like BF) or break the rules with increments and decrements.  I chose the latter as I ...
...just want to share the facts that a hexagon is a polygon with 6 sides, and the number 6 has a factor 3. This is an "advantage" to Hexagons so I hope this will be interesting.
Expanded version
   ? $ \ <
  @ ' \ . |
 ! " 1 . ( |
{ ' & . { & .
 1 \ ( ) \ $
  . . . . .
   . . . .

? gets the input, and $ skips a mirror then we hit < the branch.
If the number is <=0 it goes to the corner then to {!@ which prints the "counter" (explained below) and ends the program.
(Else) If it is >0,

decrement it and increase the counter by 1 (located relatively at
{ as left neighbour and goes back with ").
Step back to the
right and copy.
Step back to the right and copy again.
Goes back to the branch after a few reflections.

Anyone who wants to understand how this ends with graphics? I hope there is someone who wants to know more about Hexagony and know why keep stepping back to the right will in turn accumulates the counter. :P
I can't use the operators +-*/%.  Can I use :? (The integer division) Obviously not - I'll be breaking the rules.  Sadly I am already breaking the rules with increments and decrements.  So I imposed myself to an unintended rule - not using / as an operator for reflection :) Whole program is +-*/%-free.  May need a side length 5 hexagon to make one that can take care of the negatives...
Oh I just love hexagons.
Hexagon Edition, also 28, another way to get back into the loop.
?$|<@'\H|!"EX(|{'AG{&|O&N)\$

Python 3, 61 bytes
from numpy import*;f=lambda x:int(base_repr(x,base=3)[:-1],3)

This doesn't win, but I think it's a clever method that hasn't been used in the other Python entries, so I'm posting it here.

if using numpy import numpy;print(int(numpy.mean([x,0,0]))) for 44?

Octave/MATLAB, 7 bytes
@(x)3\x

Try it online!
I'm not entirely sure whether or not this would count as cheating. It's not using one of the specifically listed operators (+-%/*). MATLAB has a right divide operator which divides a number on the right by a number on the left.
I'll delete this answer if the consensus that it is cheating.

JavaScript (bitwise), 92 bytes
Because this is interview question, I assume they expected to see implementation of division using bitwise operations, not tricks with strings.
So here it is. Works for negative values as well.
f=(a,b)=>b?f(a^b,(a&b)<<1):a
x=prompt(s=0)
while(y=x>>2)s=f(s,y),x=f(x&3,y)
alert(f(s,x==3))

bitwise operations, not tricks with strings -- is your solution not the one heavily dependent on bitwise operations?

@JonathanFrech it is. As I mentioned in answer, I think that what was initial interview question all about.

Python 3, 29 chars
eval(str(x)+chr(47)*2+str(3))
first golf, feels cheaty to me but here goes!
other one for 44:
import numpy;print(int(numpy.mean([x,0,0])))

Technically, you're still using a forbidden operator, it's just not visible in your source.

@BenjaminUrquhart However, this viewpoint opens a deep rabbit hole: it is unlikely that the chosen Python interpreter does not contain a forbidden character, making it  -- again -- technically use one ...

PHP, 66 bytes
<?='-'[$argn<=>0].intval(substr(base_convert($argn,10,3),0,-1),3);

Try it online!
Divides by lobbing off the least significant digit in the base 3 representation of the original number.  The result is truncated (10/3 = 3), works with negative numbers and uses the PHP spaceship operator.

ReRegex, 22 bytes
a(_*)\1\1_*/$1/a#input

Takes IO in the form of unary _s via STDIN.
Simple program, matches three chunks of _'s as greedily as possible, and dumps out the first group. Remaining _'s are also matched away.
Try it online!

Ruby, 21 bytes
->n{3.step(n,3).size}

Try it online!

Scheme, 95 110 bytes
(define (h n)
  (length
   (let l ((a (iota n)))
     (if (> (length a) 2)
         (cons 1 (l (cdddr a)))
         '()))))

My original attempt using base conversion:
(define (g n)
  (string->number
   (list->string
    (reverse
     (cdr
      (reverse
       (string->list
        (number->string n 3))))))
   3))

I can't think of a better way of removing the last character from the string.


text:
Generate a (completely deterministic) pseudorandom bit stream
Inspired by Random with your hands tied:

The Goal
The goal of this challenge is to write a program that generates a pseudorandom bit stream, which is a string of 1s and 0s that appears to be purely random, but is actually generated in a deterministic way. Your program should output a string of 1 and 0s (with optional whitespace) and should pass the following requirements:

Given unlimited time and memory, your program must continue to output a string of 1s and 0s forever
Your program must output more than 1000 random bits in about one minute, on a reasonable machine. If this requirement is impossible, then I will lessen it.
The string of bits can repeat, but the length of the repeating section must be more than 1000 bits.
The string of bits must pass as many of the randomness tests (described below) as possible.
The program must not take any input from any external sources or use any built-in rand()-like function.
Because of the above requirement, the program must output the same exact string of bits each time that it is run.

Randomness Test #1
The string of pseudorandom bits must not include any obvious pattern upon visual inspection.
Randomness Test #2 (subject to change based on comments)
The string of bits must contain an equal distribution of 1s and 0s. To test this (and other things too), the stream of bits is broken into segments that are 3 bits long, such as 101|111|001.
Out of all of these segments, 1/8 of them should have three 1s and no 0s, 3/8 of them should have two 1s and one 0, 3/8 of them should have one 1 and two 0s, and 1/8 of them should have no 1s and three 0s.
Randomness Test #3
A "run" is defined as a consecutive series of bits that all have the same value. The string 1001001110 has three runs of size 1 (1..1.....0), two runs of size 2 (.00.00....) and one run of size 3 (......111.).  Notice that runs do not overlap.
Out of a string of 1000 random bits, there should be about 250 runs of size 1, 125 runs of size 2, 62 runs of size 3, etc. In general, for run size R, there should be about 1000/(2**(R+1)) runs of that size.
Randomness Test #4
The first 840 bits are split into two halves of 420 bits each. Each bit on the first half is compared to the corresponding bit on the second half. The two bits should match about fifty percent of the time.

Here is the source code of a Perl program that performs tests 2 through 4. As of now, it requires that the string of bits not contain any whitespace.

Objective Winning Criterion Time!
The winner is the program that passes all of the 6 requirements and all of the randomness tests to the degree that it is indistinguishable from randomness. If multiple programs accomplish this, then the one that takes the longest amount of time to repeat will win. If multiple programs accomplish this, then I might have to find more randomness tests to act as tie-breakers.

#2 and #3 aren't really very good criteria for randomness. For #2 especially, a random sample will probably not exhibit this characteristic. Maybe you can do a larger sample size? I would suggest something between 100 and 300.

A better measurement method would be a moving average, as the mean over a large window on the bitstream will not change much (and should be around 0.5)

@JoelCornett Thanks for the advice. I don't know much about randomness tests. I'll change #2 to something else, and I'm reading about moving averages.

No problem. Random sequences tend to clump and not be uniformly distributed, this is a fact that is sometimes used in accounting to detect fraud. (Fraudulent numbers will often be too evenly distributed, because the people inventing them mistake uniformity for randomness)

Can I use built in crypto functions (Such as AES or SHA-2)?

There are standard randomness suites, such as diehard and dieharder. But I haven't used any of them.

thanks for fixing up my question; much better :) - I did want to see some of the fun ideas on this one!

@JoelCornett there was an early episode of Numb3rs about that i think...

Mathematica 78 53 chars
The digits of the binary representation of Pi seem to behave as if they are chaotically produced although this is unproven.
The following simple routine deterministically returns as a string the binary digits of pi, corresponding to d decimal digits:
f[d_]:=ToString@FromDigits@RealDigits[N[Pi,d],2][[1]]

Usage
If we request the counterpart of 301 decimal digits of Pi, we receive 1000 binary digits.
f[301]
StringLength[%]

(* out *)
1100100100001111110110101010001000100001011010001100001000110100110001001100011001100010100010111000000011011100000111001101000100101001000000100100111000001000100010100110011111001100011101000000001000001011101111101010011000111011000100111001101100100010010100010100101000001000011110011000111000110100000001001101110111101111100101010001100110110011110011010011101001000011000110110011000000101011000010100110110111110010010111110001010000110111010011111110000100110101011011010110110101010001110000100100010111100100100001011011010101110110011000100101111001111110110001101111010001001100010000101110100110100110001101111110110101101011000010111111111101011100101101101111010000000110101101111110110111101110001110000110101111111011010110101000100110011111101001011010111010011111001001000001000101111100010010110001111111100110010010010010100001100110010100011110110011100100010110110011110111000010000000000111110010111000101000010110001110111111000001011001100011011010010010000011011000011100011

1000 (* characters *)

Because Pi is an irrational number, there is no period.  However, there will be practical constraints due to the hardware one is running.
Test 1
Looks good to me.
Test 2
d=301;
Partition[RealDigits[N[Pi,d],2][[1]],{3}];
Tally[%]
(* out *)
{{{1,1,0},35},{{0,1,0},45},{{0,0,0},41},{{1,1,1},40},
{{0,1,1},50},{{1,0,1},32},{{1,0,0},43},{{0,0,1},47}}

More thorough check:
d=10^6;
Partition[RealDigits[N[Pi,d],2][[1]],{3}];
Tally[%]

{{{1,1,0},138565},{{0,1,0},138146},{{0,0,0},138260},{{1,1,1},138427},
{{0,1,1},139119}, {{1,0,1},138404},{{1,0,0},137926},{{0,0,1},138462}}

Test 3: Runs
d=10^6;
res3=SortBy[Tally@Split@RealDigits[N[Pi,d],2][[1]],Last]/.{a_,b_}:> {Length[a],b}
ListPlot[res3 ,AxesLabel-> {"Run Length","Runs"},AxesOrigin->{0,0}]

I ran a large number of cases to systematically check out the distribution of runs.
In approximately 3 million binary digits, there were 830k runs of 1, 416k runs of 2, 208k runs of 3, 104k runs of 4, etc.

Test 4: Matching of first and second half of data
The matches are the 212 cases of 0 and 2; the mismatches are the 208 cases where the sum of the respective digits is 1.
d=301;
Tally[Plus@@Partition[Take[RealDigits[N[Pi,d],2][[1]],840],420]]

(* out *)
{{1,208},{0,108},{2,104}}

Timing
It takes under two seconds to calculate  3321928 binary digits (corresponding to 10^6 decimal digits).
(r=f[10^6]);//AbsoluteTiming
StringLength[r]

(*out*)
{1.785928,Null}
3321928

I knew someone would do this...

Low-hanging fruit, right?

Couldn't you use e instead of pi to save one byte?

Is e distributed chaotically?

C, 61
main(s,n){for(n=1u<<31;putchar((s%=n)/(n/2)&1|48);s*=65539);}

Yeah, I know it's not code golf. This is obviously rather an anti-solution... but it sure enough fulfills your criteria.

$ ./a.out | head -c840
  000000001000111101100110110011100100011101110001101001101110011101100111010111010010001001110001111110010001010101101000110101000011110010100101001101110100011111000101000110000111100100010101010100110101101010001110101000011011001010111011110110101000001110011000010100001111110110001000000101100011000110000010110011000010101101011100010011011111111100001010111110111010110001000010110111000010101001000011001001110110001001101011011110111011010100000000001001010100111000000100010011110001010111001110101111100110110111010001101001100000101000111000101000110100001111010110100001100110011011110001011011100010111011100001110100110001010011001110001010110100111111111010110101100110000101111111111000111101100011000111010111010100110001001110101110100011101110001100110110000001100101110100101000101011100000110111101101100110000000101110
  $ ./a.out | head -c840 | perl tester.pl
  Test 2: 1 (1) 2.93333333333333 (3) 3.1 (3) 0.966666666666667 (1)
  Test 3:  214 99 71 24 7 5 1 1 2 2
  Test 4: 0.495238095238095

Period length is 2²⁹.

This goes to show how hard it is to tell randomness from something that is widely known to be one of the worst random number generators in existence. +1.

Python, 90
g=[19]
print(''.join("01"[(g.append((11*g[-1]+13)%1024)or g[-1])>512]for i in range(1000)))

g is the seed value. Random sampling exhibits a remarkably normal distribution repeated random sampling of sample means yielded a mean of 0.506 and a a standard deviation of .0473 (sample size of 1000). Unfortunately, randomness is highly sensitive to initial seed. The seed in the above code gave me the best randomness :p
UPDATE
Let's see how this code holds up to the OP's tests:
Test #1
This one's a bit subjective... but it looks pretty irregular to me.
Test #2

Three 1's: 0.141
Two 1's: 0.371
One 1: 0.353
Zero 1's: 0.135

Test #3
Runs by size:
8: 11
7: 3
6: 7
5: 13
4: 32
3: 67
2: 119
1: 216

Test #4

 Ratio of equalities: 0.94  This is a typo. Will update with the correct number soon.

You can remove the whitespace before 'for'.

Haskell 74 58
main=print$iterate(read.take 9.show.(^3))7>>=show.(`mod`2)

Thanks to shiona for the simplification.
Results:

$ ~/golf$ ./pseudorandom | head -c 1000
  111110110101011110001011110101011110001111011001110101100100111000100100000011000100011101010111000000001110100111100010110000100000001001111011100001101101001111110100111011111110011011101111010110001110011100010000001011011100010111011110011110100110100000110110010011101010001111101011111110000110110110011111011101000011110010000011011010011110110100010011100011011111011010110001100111100100100001110100001110111011111000001101001010100001100111010111011011011001110000100000100000010111011010111011111011011101001100100011111101110101101010111101001111110101110101001011111011111100111110001001001010001011100100101000010101011001101011011001100111101010001110001011110001011111110110100110011000010101100010011011010100000110100001000010110110111101101010000001110001100011010100000011111010111100101110101001000111001000000101111110010110001011011000011111011001100001101000101001111000101011101010001010110010111111110111111101000111010001001010010011101011100101011101000101101000010101100
./pseudorandom | head -c 1000 | perl test.pl
Test 2: 0.966666666666667 (1) 2.4 (3) 3.3 (3) 1.33333333333333 (1)
Test 3:  260 108 66 33 15 11 5 2
Test 4: 0.495238095238095

This is also a terrible pseudo-random generator (similar to one used by von-Neuman). For those that were not aware concatMap == (=<<) == flip . (>>=) (for lists)

You can replace \x->if odd x then"1"else"0" with show.(`mod`2).

C, 52 chars
main(a){for(a=1;putchar(48+a%2);a=a/2^-(a%2)&576);}

This is a 10 bit LFSR, test results:
$ ./a.out |head -c 1000 | perl randtest.pl
Test 2: 1.13333333333333 (1) 2.86666666666667 (3) 3.16666666666667 (3) 0.833333333333333 (1)
Test 3:  251 122 64 32 16 8 4 2  1
Test 4: 0.466666666666667

a should start out as 1, (assuming it's called with no arguments). Also you could stick the a= in the middle, something like a=a/2^-!putchar(49-a%2)%576 (taking some liberties with the algorithm)

@walpen: My initial implementation didn't set a, I changed it because of "The program must not take any input from any external sources"

Java, 371 317
Based on a 128 bit LFSR (bit taps are from xilinx app note 52)
EDIT: I was not satisfied with using BigInteger so this version does not. Saved some characters. Output might be a little less random as I could not think of a good 'seeding' method.
New Code: Arguments: BITS_TO_PRINT
class R{public static void main(String[]a){int L=65536;int[]v={0,128,126,101,99};int[]b=new int[L];for(int x=0;x<L;x++)b[x]=(x*x)&1;for(int i=0;i<Integer.parseInt(a[0])+L;i++){if(1!=(b[v[1]]^b[v[2]]^b[v[3]]^b[v[4]]))b[v[0]]=1;else b[v[0]]=0;if(i>L)System.out.print(b[v[0]]);for(int j=0;j<5;j++)v[j]=(v[j]-1)&(L-1);}}}

Old Version:
Arguments: SEED, BITS_TO_PRINT
import java.math.BigInteger;class R{public static void main(String[]a){BigInteger v=new BigInteger(a[0]);BigInteger m=new BigInteger("ffffffffffffffffffffffffffffffff",16);for(int i=Integer.parseInt(a[1]);i>0;i--){v=v.shiftLeft(1);if(!(v.testBit(128)^v.testBit(126)^v.testBit(101)^v.testBit(99))){v=v.setBit(0);}v=v.and(m);java.lang.System.out.print(v.testBit(0)?1:0);}}}

New Version: Example output, bits=100:
011001100111000110010100100111011100100111000111001111110110001001100000100111111010111001100100011

BTW, I assume that both Noah accounts from this post are the same person. If that's so, you can ask a moderator to merge them at http://meta.codegolf.stackexchange.com/

The question is essentially equivalent to "implement a stream cipher". So I implement RC4, since it's relatively simple.
I use no key, and drop the first 100000 bits, because the beginning of RC4 is a bit biased, especially since I skipped the key schedule. But I'd expect it to pass your test even without that (saving 20 chars of code).
Normally one would output a full byte per cycle, but converting to binary is rather ugly in C#, so I simply discard everything except the least significant bit.
var s=Enumerable.Range(0,256).ToArray();
byte i=0,j=0;
for(int k=0;;k++)
{
    i++;
    j+=(byte)s[i];
    var t=s[i];s[i]=s[j];s[j]=t;
    if(k>99999)
        Console.Write(s[i]+s[j]&1);
}

Or without spaces:
var s=Enumerable.Range(0,256).ToArray();byte i=0,j=0;for(int k=0;;k++){i++;j+=(byte)s[i];var t=s[i];s[i]=s[j];s[j]=t;if(k>99999)Console.Write(s[i]+s[j]&1);}

C#, 156 chars, works in LinqPad's statement mode. For a full C# program add the usual boilerplate.

We could also use built in crypto primitives(Cheater solution):
var h=SHA256.Create();for(BigInteger i=0;;i++){Console.Write(h.ComputeHash(i.ToByteArray())[0]%2);}

(C#, 99 chars, works in LinqPad's statement mode. For the normal C# compiler you'll need to add a bit of boilerplate)
The output of cryptographic hash functions is designed to be indistinguishable from random data, so I expect it to pass all randomness tests(die harder,...) you throw at it, but I'm too lazy to test.

Sage/Python
This program prints the rightmost binary digits that are common to every sufficiently tall exponentiation tower of form 3333...  For all that could ever be feasibly generated, these are the rightmost binary digits of Graham's number. The digit sequence is infinite, and is not periodic.
m = 1; x = 3; last = 0
while True:
    m *= 2; x = pow(3,x,m); l = len(bin(x))
    print '1' if l > last else '0',
    last = l

For 1000 digits, this took less than 2 seconds; however, the time will increase much faster than linearly in the number of digits.
The test results using the OP's program are
Test 2: 1.26666666666667 (1) 3.16666666666667 (3) 2.8 (3) 0.766666666666667 (1)
Test 3:  268 126 61 30 20 7 2  1 1
Test 4: 0.466666666666667

(See Are the rightmost digits of G random? for more than 32000 digits and additional statistical tests.)

JavaScript - 1ms to 2ms for 1000 pseudo-random bits (139ms to 153ms for 100000 bits)
This solution uses the fact that square roots are irrational, and thus pretty much random.  Basically, it takes the square root of 2 to start, converts it to binary, throws out the leading part that matched the previous root, appends that to the random string, repeats with the next higher number (or back to 2 if the number repeated and was at least 30 bits long), and returns the random string once it is long enough.
var getDeterministicPseudoRandString = function(length){
    var randString = '';

    var i = 2;
    var prevRand = '';

    outerLoop:
    while(randString.length < length){
        var nextRand, nextFullRand = Math.sqrt(i++).toString(2).substring(1).replace('.', '');
        nextRand = nextFullRand;
        for(var j = prevRand.length; j > 0; j--){
            var replaceString = prevRand.substring(0, j);

            nextRand = nextFullRand;

            if(nextFullRand.indexOf(replaceString) == 0){
                if(j == prevRand.length && j > 30){
                    //start i over at 2
                    console.log('max i reached: ' + i);

                    i = 2;
                    continue outerLoop;
                } else {
                    nextRand = nextFullRand.replace(replaceString, '');
                }

                break;
            }
        }
        prevRand = nextFullRand;

        randString += nextRand;
    }

    return randString.substring(0, length);//Return the substring with the appropriate length
};

I haven't ran it through the tests yet, but I imagine it will do well on them.  Here's a fiddle so you can see it in action.  For my times, I just ran the program several times and took the fastest and slowest values as the ranges.

perl, 44 bytes
I know this isn't code golf, but I've always been a fan of taking the low order bits of a simple quadratic function, eg:
$x=1/7;print substr($x*=4-4*$x,9,1)%2while 1

Period is longer than 3 billion, but I've run out of disk space to calculate more.

you can save 3 chars by juxtaposing numeric constants and keywords and also distributing that 4: $x=1/7;print substr($x*=4-4*$x,9,1)%2while 1

Python
import hashlib
x=''
while 1:
    h=hashlib.sha512()
    h.update(x)
    x=h.digest()
    print ord(x[0])%2

Should have a period of about 2^512.

source: Stack Exchange

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

sort: votes


text:
Square-free semiprime counting
Definition

A square-free semiprime is a natural number that is the product of two distinct prime numbers.

The task
Given a natural number n, count all square-free semiprimes less than or equal to n.
Details
Please write a function or procedure that accepts a single integer parameter and counts all square-free semiprimes less than or equal to its parameter. The count must either be a return value of a function call or be printed to STDOUT.
Scoring
The answer with the fewest number of characters wins.
In the event of a tie, the following criteria will be used in order:

Tallest person

Best time-complexity

Worst space-complexity

Examples
f(1)     = 0
f(62)    = 18
f(420)   = 124
f(10000) = 2600

http://oeis.org/A180074 ?

oops, sorry, but no that sequence is not quite right due to the congruence restriction (e.g., 35=57 and 55=511 are not included). I will add a few example solutions to this particular problem momentarily.

http://oeis.org/A006881

What happens if a language doesn't have STDOUT (like javascript)? Use console.log?

@Inkbug isn't javascript capable of returning a value from a function?

@ardnew Oh, I missed that. Sorry.

J, 50 40 38 37 characters
f=:3 :'+/y<:}.~.,(~:/**/)~p:i._1&p:y'

Usage:
   f 1
0
   f 62
18
   f 420
124
   f 10000
2600

With thanks to FUZxxl.
Performance test
   showtotal_jpm_ ''[f 1[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000046│0.000046│100.0│100 │1  │
│[total]│      │        │0.000046│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000095│0.000095│100.0│100 │2  │
│[total]│      │        │0.000095│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000383│0.000383│100.0│100 │3  │
│[total]│      │        │0.000383│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[f 10000[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.084847│0.084847│100.0│100 │4  │
│[total]│      │        │0.084847│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[f 10000[f 50000[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │5.014691│5.014691│100.0│100 │5  │
│[total]│      │        │5.014691│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘

I'm no theoretician as has been seen here in the past, but I think the time complexity is something like O(np2) where np is the number of primes up to and including the input number n. This is based on the assumption that the complexity of my method (generating a very large multiplication table) far outweighs the complexity of the prime generating function built in to J.
Explanation
f=:3 :'...' declares a (monadic) verb (function). The input to the verb is represented by y within the verb definition.
p:i._1&p:y The p: verb is the multi purpose primes verb, and it's used in two different ways here: _1&p:y returns the number of primes less than y then p:i. generates every one of them. Using 10 as input:
   p:i._1&p:10
2 3 5 7

(~:/**/)~ generates the table I spoke of earlier. */ generates a multiplication table, ~:/ generates a not-equal table (to eliminate the squares) and both of these are multiplied together. Using our previous output as input:
   */~2 3 5 7
 4  6 10 14
 6  9 15 21
10 15 25 35
14 21 35 49

   ~:/~2 3 5 7
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0

   (~:/**/)~2 3 5 7
 0  6 10 14
 6  0 15 21
10 15  0 35
14 21 35  0

}.~., now we turn the numbers into one list , get the unique values ~. and remove the 0 at the start }.
   }.~.,(~:/**/)~2 3 5 7
6 10 14 15 21 35

y<: a comparison with the original input to check which values are valid:
   10<:6 10 14 15 21 35
1 1 0 0 0 0

+/ and then sum that to get the answer.
   +/1 1 0 0 0 0
2

Do you have a phony version of this program (phony as the opposite of tacit)? 13 is not always giving the most efficient tacit code.

No, I didn't use 13 in this case - though I think I probably did what it would have done had I tried. The code is basically: +/-.x<}.~.,(~:/~*[*/])p:i._1&p:[x=.n where n is the input.

Why not just f=:3 :'+/-.y<}.~.,(~:/~*[*/])p:i._1&p:y' for 40 characters?

Thanks, I never even considered using 3 :'...'

Would you publish some timing results so we can judge the efficiency of the program?

@DavidCarraher I've added some performance stats.

Would you like to add some notes about the algorithm?

@FUZxxl I've added an explanation.

Lesser than-or-equal is <: fyi. Have a look at the vocabulary for more information.

@FUZxxl D'oh! Missed that. Always think of <: as decrement. Thanks.

Mathematica 65 64 55 51 47 39
Code
The following counts the number of  square-free semiprimes less than or equal to n:
FactorInteger@Range@n~Count~{a={_,1},a}

Any square-free semiprime factors into a structure of the form: {{p,1}{q,1}}
For example,
FactorInteger@221
(* out *)
{{13, 1},{17, 1}}

The routine simply counts the numbers in the desired range that have this structure of factors.

Usage
n=62;
FactorInteger@Range@n~Count~{a={_,1},a}

(* out *)
18

Timing: All the given examples
FactorInteger@Range@#~Count~{a = {_, 1}, a} & /@ {1, 62, 420, 10^4} // Timing

(* out *)
{0.038278, {0, 18, 124, 2600}}

Timing: n=10^6
It takes under four seconds to count the number of square-free semi-primes less than or equal to one million.
n=10^6;
FactorInteger@Range@n~Count~{a = {_, 1}, a}//Timing
(* out *)
{3.65167, 209867}

Fantastic, concise solution

@ardnew Thanks. I enjoyed the challenge.

Nice! Question: are those space characters around the = and after the , actually needed syntactically?

@ToddLehman,  You are right.  I removed them.  (They had not been counted so the byte count stays the same.)

Python, 115
r=range
p=lambda x:all(x%i for i in r(2,x))
f=lambda x:sum([i*j<=x and p(j)and p(i)for i in r(2,x)for j in r(2,i)])

f=lambda x:sum([(i*j<=x)&p(j)&p(i)for i in r(2,x)for j in r(2,i)]) saves 5 characters.

@beary605: Thanks, but I think that it will take way too long without short circuiting.

voting you up. too many thoughts about itertools in my head.

Jelly, 7 bytes
ŒcfÆf€L

Try it online!
How it works
ŒcfÆf€L  Main link. Argument: n

Œc       Generate all 2-combinations of [1, ..., n], i.e., all pairs [a, b] such
         that 1 ≤ a < b ≤ n.
   Æf€   Compute the prime factorization of each k in [1, ..., n].
  f      Filter; keep only results that appear to the left and to the right.
      L  Take the length.

Wow, you made my attempt look embarrassing. Thanks for the ideas!

Python (139)
from itertools import*;s=lambda n:sum(x*y<=n and x<y for x,y in product(filter(lambda x:all(x%i for i in range(2,x)),range(2,n)),repeat=2))

Please provide some sample results so competitors could test their programs.

see, you didn't even need the examples! :^)

Ruby 82
z=->n{[*2..n].select{|r|(2...r).all?{|m|r%m>0}}.combination(2).count{|a,b|a*b<=n}}

Demo: http://ideone.com/cnm1Z

Shell, 40

#!/bin/sh

seq $1|factor|awk 'NF==3&&$2!=$3'|wc -l

#old, 61
#seq $1|factor|awk 'BEGIN{a=0}NF==3&&$2!=$3{a++}END{print a}'

Usage:

$ ./count 1
0
$ ./count 420
124
$ ./count 10000
2600
$ time ./cnt.sh 1000000
209867

real    0m23.956s
user    0m23.601s
sys     0m0.404s

Python 139
def f(n):
 p=[];c=0
 for i in range(2,n+1):
    if all(i%x for x in p):p+=[i]
    c+=any((0,j)[i/j<j]for j in p if i%j==0 and i/j in p)
 return c

Golfscript 64
~:ß,{:§,{)§\%!},,2=},0+:©{©{1$}%\;2/}%{+}*{..~=\~*ß>+\0?)+!},,2/

Online demo here
Note: In the demo above I excluded the 420 and 10000 test cases. Due to the extremely inefficient primality test, it's not possible to get the program to execute for these inputs in less than 5 seconds.

Jelly, 14 13 bytes
RÆEḟ0⁼1,1$Ɗ€S

Try it online!
RÆEḟ0⁼1,1$Ɗ€S    main function:
RÆE             get the prime factorization Exponents on each of the Range from 1 to N,
          Ɗ€    apply the preceding 1-arg function composition (3 funcs in a row) to each of the prime factorizations:
                (the function is a monadic semiprime checker, as per DavidC's algorithm)
    ḟ0          check if the factors minus the zero exponents...
      ⁼1,1$      ...are equal to the list [1,1]
             S   take the Sum of those results, or number of successes!

Constructive criticism welcomed!

This combination of ⁼ and S can be turned into a use of ċ (Count). You can get down to 10 bytes using it. I'll let you work it out!

Python 2/3, 95 94 bytes
lambda n:sum(map(F,range(n+1)))
F=lambda x,v=2:sum(x%i<1and(F(i,0)or 3)for i in range(2,x))==v

Try it online!
Posted in a 6 year old challenge because it sets a new Python record, an IMO it's a pretty interesting approach.
Explanation
lambda n:sum(map(F,range(n+1)))           # Main function, maps `F` ("is it a semiprime?")
                                          #  over the range [0, n]
F=lambda x,v=2:                           # Helper function; "Does `x` factor into `v`
                                          #  distinct prime numbers smaller than itself?"
  sum(                                    # Sum over all numbers `i` smaller than `x`
    x%i<1                                 # If `i` divides `x`,
    and                                   #  then
    (F(i,0)                               #  add 1 if `i` is prime (note that `F(i,0)`
                                          #  is just a primality test for `i`!)
    or 3)                                 #  or `3` if `i` is not prime (to make `F`
                                          #  return `False`)
  for i in range(2,x))
  ==v                                     # Check if there were exactly `v` distinct prime
                                          #  factors smaller than `x`, each with
                                          #  multiplicity 1

Python 2/3 (PyPy), 88 82 81 bytes
lambda n:sum(sum(x%i<1and(x/i%i>0or 9)for i in range(2,x))==2for x in range(n+1))

Try it online!
Based on a 92-byte golf by Value Ink. PyPy is needed to correctly interpret 0or, because standard Python sees this as an attempt at an octal number.

92 bytes by checking square divisibility instead of primality

Pari/GP, 61 bytes
Golfed version. Try it online!
f(n)={c=0;forprime(p=2,sqrtint(n),forprime(q=p+1,n/p,c++));c}

Ungolfed version. Try it online!
squareFreeSemiPrimes(n) = {
    local(count = 0);
    forprime(p = 2, sqrtint(n),
        forprime(q = p+1, n/p,
            count++
        )
    );
    return(count);
}
\\ Here is an example of how to call the function
print(squareFreeSemiPrimes(1))
print(squareFreeSemiPrimes(62))
print(squareFreeSemiPrimes(420))
print(squareFreeSemiPrimes(10000))

Perl 6, 58 45 bytes
Thanks to Jo King for -13 bytes.
{+grep {3==.grep($_%%*)&&.all³-$_}o^*,1..$_}

Takes advantage of the fact that integers with four factors are either square-free semiprimes or perfect cubes.
Try it online!

45 bytes

Stax, 8 bytes
ßº@N¬Që↔

Run and debug it
Unpacked, ungolfed, and commented, it looks like this.
F       for 1..n run the rest of the program
  :F    get distinct prime factors
  2(    trim/pad factor list to length 2
  :*    compute product of list
  _/    integer divide by initial number (yielding 0 or 1)
  +     add to running total

Run this one

Brachylog, 7 bytes
{≥ḋĊ≠}ᶜ

Try it online!
           The output is
{    }ᶜ    the number of ways in which you could
 ≥         choose a number less than or equal to
           the input
  ḋ        such that its prime factorization
   Ċ       is length 2
    ≠      with no duplicates.

Retina, 58 bytes
_
¶_$`
%(`$
$"
,,`_(?=(__+)¶\1+$)
¶1$'
)C`1(?!(__+)\1+¶)
2

Try it online!
Takes as input unary with _ as tally mark
Explanation
A number is a square-free semi-prime if its largest and smallest factor, excluding itself and 1, are both primes.
_
¶_$`

Takes the input and generate each unary number less than or equal to it, each on its own line
%(`

Then, for each number ...
$
$"
,,`_(?=(__+)¶\1+$)
¶1$'

Find its smallest and largest factor, excluding itself an 1 ...
)C`1(?!(__+)\1+¶)

and count the number of them that is prime. Since the smallest factor must be a prime, this returns 1 or 2
2

Count the total number of 2's

Python 2, 105 104 bytes
lambda m:sum(reduce(lambda(a,v),p:(v*(a+(n%p<1)),v>0<n%p**2),range(2,n),(0,1))[0]==2for n in range(m+1))

Try it online!
1 byte thx to squid

(p*p) can be p**2

APL(NARS), chars 26, bytes 52
{≢b/⍨{(⍵≡∪⍵)∧2=≢⍵}¨b←π¨⍳⍵}

test:
  f←{≢b/⍨{(⍵≡∪⍵)∧2=≢⍵}¨b←π¨⍳⍵}
  f 1
0
  f 9
1
  f 62
18
  f 420
124
  f 1000
288
  f 10000
2600
  f 100000
23313

this is a longer alternative  (59 chars that i would prefer)
r←h w;n;t
n←4⋄r←0
n+←1⋄→0×⍳w<n⋄→2×⍳(2≠≢t)∨2≠≢∪t←πn⋄r+←1⋄→2

test:
  h 1000000
209867

Ruby -rprime, 64 bytes
I know that there's another Ruby solution here, but I didn't want to bump it with comments since it was answered in 2012... and as it turns out, using a program flag counts it as a different language, so I guess this technically isn't "Ruby" anyhow.
Try it online!
Explanation
->n{(1..n).count{|i|m=i.prime_division;m.size|m.sum(&:last)==2}}
->n{                                    # Anonymous lambda
    (1..n).count{|i|                    # Count all from 1 to `n` that match
                                        # the following condition
                m=i.prime_division;     # Get the prime factors of `i` as
                                        #  base-exponent pairs (e.g. [2,3])
                m.size                  # Size of factors (# of distinct primes)
                      |                 # bit-or with...
                       m.sum(&:last)    # Sum of the last elements in the pairs
                                        #  (the sum of the exponents)
                                    ==2 # Check if that equals 2 and return.
                                        # Because 2 is 0b10, the bit-or means
                                        #  that the condition is true iff both
                                        #  are either 2 or 0, but because this
                                        #  is a prime factorization, it is
                                        #  impossible to have the number of
                                        #  distinct primes or the sum of the
                                        #  exponents to equal 0 for any number
                                        #  > 1. (And for 1, size|sum == 0.)
    }                                   # End count block
}                                       # End lambda

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

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