Perl 6: 17
The first thing that comes to mind is
[+] 1337.base(2).comb; # returns 6
Although this doesn't have any arbitrary limits ( the only limits are how much memory you have, and how long you are willing to wait )
[+] ( uint64.Range.max * 2 + 1 ).base(2).comb; # returns 65
# 340282366920938463463374607431768211455
my $uint128-max = :2( 1 x 128 );
[+] $uint128-max.base(2).comb; # returns 128
my $uint8192-max = :2( 1 x 8192 ); # 2467 digit Int
[+] $uint8192-max.base(2).comb; # returns 8192 (takes about a second currently)
Without making it into a Callable the shortest way to write this is to put the Int into the "default" variable $_
. ( .method
is always short for $_.method
)
$_ = 1337;
[+] .base(2).comb;
given 1337 { # Perl6's with/switch statement
[+] .base(2).comb
}
[+] .base(2).comb given 1337; # ditto
if 1337 -> $_ { # pointy block
[+] .base(2).comb
}
If you want to create a Callable you could just put it into a Block.
my $code-ref = {[+] .base(2).comb};
# if it is called with an argument it places it in $_
# if called without an argument uses the $_ from an outer scope
If you really want to call it as a normal subroutine:
my &f={[+] .base(2).comb}; # sub f($_){[+] .base(2).comb}
say f 1337; # 6
$_ = 1337;
say f; # 6
Based on your requirements I'd guess that the answer you are looking for is:
[+] .base(2).comb
This assumes that the value is already in $_
. It would most likely be the last statement in a subroutine, the right side of an assignment, or an argument to a subroutine or method. ( Otherwise it calculates the result only to throw it away, unless the compiler notices that the result is unused )
In case you were wondering [+] 1, 2, 3
can be considered short for (1,2,3).reduce(&[+])
.
Where &[+]
is short for &infix:< + >
the collection of multi subs available in the current scope that are responsible for the numerical infix addition operator +
.
Related but not dupe: 1 2
– Sp3000 – 2015-03-17T00:43:12.2333 4 – jimmy23013 – 2015-03-17T00:53:42.030
2Tip: just as the some of digits in a number is congruent to the number mod 9, the some of bits equals the number mod 1. – PyRulez – 2015-03-17T16:11:07.683
8@PyRulez Any number is zero modulo 1. – Thomas – 2015-03-17T17:18:57.103
1Hi, you have chosen a wrong answer as accepted answer (by default tie breaker logic of earliest post). – Optimizer – 2015-03-18T09:11:41.460
4@Thomas I never said it was a helpful tip. – PyRulez – 2015-03-18T15:40:27.440
2Why is this question attracting close votes AFTER most of the answers have been posted? Close voters please indicate your reason in the comments. If it is the acceptance of es1024's (very clever) 4-byte answer which does not comply with standard loopholes (because it uses a builtin) please state that this is the reason. Otherwise, what is it? – Level River St – 2015-03-18T15:53:52.980
@Thomas Slight correction- any integer is zero modulo 1. – SuperJedi224 – 2016-01-29T00:20:58.713