704 Factors of Two in Binomial Coefficients.pl 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 03 March 2020
  4. # https://github.com/trizen
  5. # Factors of Two in Binomial Coefficients
  6. # https://projecteuler.net/problem=704
  7. # Runtime: 0.031s
  8. # The maximal value of m for a given n-1, is given by:
  9. # A053645(n) = n - 2^floor(log_2(n))
  10. # The valuation of 2 in binomial(n-1,m), for the value of m defined above, is given by:
  11. # A119387(n) = floor(log_2(n)) - valuation(n,2)
  12. # Then the value of F(n) is given by:
  13. # F(n) = A119387(n+1)
  14. # To find S(n) = Sum_{k=1..n} F(k), we first define:
  15. # A(n) = A061168(n) = Sum_{k=1..n} floor(log_2(k))
  16. # B(n) = A011371(n) = Sum_{k=1..n} valuation(k,2)
  17. # Then we have:
  18. # S(n) = A(n+1) - B(n+1)
  19. # For computing A(n) and B(n) efficiently, we have the following formulas:
  20. # A(n) = (n+1)*floor(log_2(n)) - 2*(2^floor(log_2(n)) - 1)
  21. # B(n) = n - hammingweight(n)
  22. # See also:
  23. # https://oeis.org/A053645
  24. # https://oeis.org/A119387
  25. # https://oeis.org/A061168
  26. # https://oeis.org/A011371
  27. use 5.020;
  28. use warnings;
  29. use ntheory qw(:all);
  30. use experimental qw(signatures);
  31. sub A($n) {
  32. ($n+1)*logint($n,2) - 2*(powint(2, logint($n, 2)) - 1);
  33. }
  34. sub B($n) {
  35. $n - hammingweight($n);
  36. }
  37. sub S($n) {
  38. A($n+1) - B($n+1);
  39. }
  40. say S(powint(10, 16));
  41. __END__
  42. S(10^(10^5)) = 3321898588...7585514573 (100006 digits)
  43. S(10^(10^6)) = 3321925127...5321046359 (1000007 digits)
  44. S(10^(10^7)) = 3321927796...6616569057 (10000008 digits)
  45. S(10^(10^8)) = 3321928065...3266366113 (100000009 digits)