Tau function

From Rosetta Code
Revision as of 10:50, 21 December 2020 by Simonjsaunders (talk | contribs) (Added C++ solution)
Tau function is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Given a positive integer, count the number of its positive divisors.


Task

Show the result for the first 100 positive integers.


Related task



C++

<lang cpp>#include <iomanip>

  1. include <iostream>

// See https://en.wikipedia.org/wiki/Divisor_function unsigned int divisor_count(unsigned int n) {

   unsigned int total = 1;
   // Deal with powers of 2 first
   for (; (n & 1) == 0; n >>= 1)
       ++total;
   // Odd prime factors up to the square root
   for (unsigned int p = 3; p * p <= n; p += 2) {
       unsigned int count = 1;
       for (; n % p == 0; n /= p)
           ++count;
       total *= count;
   }
   // If n > 1 then it's prime
   if (n > 1)
       total *= 2;
   return total;

}

int main() {

   const unsigned int limit = 100;
   std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
   for (unsigned int n = 1; n <= limit; ++n) {
       std::cout << std::setw(3) << divisor_count(n);
       if (n % 20 == 0)
           std::cout << '\n';
   }

}</lang>

Output:
Count of divisors for the first 100 positive integers:
  1  2  2  3  2  4  2  4  3  4  2  6  2  4  4  5  2  6  2  6
  4  4  2  8  3  4  4  6  2  8  2  6  4  4  4  9  2  4  4  8
  2  8  2  6  6  4  2 10  3  6  4  6  2  8  4  8  4  4  2 12
  2  4  6  7  4  8  2  6  4  8  2 12  2  4  6  6  4  8  2 10
  5  4  2 12  4  4  4  8  2 12  4  6  4  4  4 12  2  6  6  9

Go

<lang go>package main

import "fmt"

func countDivisors(n int) int {

   count := 0
   i := 1
   k := 2
   if n%2 == 0 {
       k = 1
   }
   for i*i <= n {
       if n%i == 0 {
           count++
           j := n / i
           if j != i {
               count++
           }
       }
       i += k
   }
   return count

}

func main() {

   fmt.Println("The tau functions for the first 100 positive integers are:")
   for i := 1; i <= 100; i++ {
       fmt.Printf("%2d  ", countDivisors(i))
       if i%20 == 0 {
           fmt.Println()
       }
   }

}</lang>

Output:
The tau functions for the first 100 positive integers are:
 1   2   2   3   2   4   2   4   3   4   2   6   2   4   4   5   2   6   2   6  
 4   4   2   8   3   4   4   6   2   8   2   6   4   4   4   9   2   4   4   8  
 2   8   2   6   6   4   2  10   3   6   4   6   2   8   4   8   4   4   2  12  
 2   4   6   7   4   8   2   6   4   8   2  12   2   4   6   6   4   8   2  10  
 5   4   2  12   4   4   4   8   2  12   4   6   4   4   4  12   2   6   6   9  

Python

Using prime factorization

<lang Python>def factorize(n):

   assert(isinstance(n, int))
   if n < 0: 
       n = -n 
   if n < 2: 
       return 
   k = 0 
   while 0 == n%2: 
       k += 1 
       n //= 2 
   if 0 < k: 
       yield (2,k) 
   p = 3 
   while p*p <= n: 
       k = 0 
       while 0 == n%p: 
           k += 1 
           n //= p 
       if 0 < k: 
           yield (p,k)
       p += 2 
   if 1 < n: 
       yield (n,1) 

def tau(n):

   assert(n != 0) 
   ans = 1 
   for (p,k) in factorize(n): 
       ans *= 1 + k
   return ans

if __name__ == "__main__":

   print([tau(n) for n in range(1,101)])</lang>

Finding divisors efficiently

<lang Python>def tau(n):

   assert(isinstance(n, int) and 0 < n)
   ans, i, j = 0, 1, 1
   while i*i <= n:
       if 0 == n%i:
           ans += 1
           j = n//i
           if j != i:
               ans += 1
       i += 1
   return ans

if __name__ == "__main__":

   print([tau(n) for n in range(1,101)])</lang>
Output:
[1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 4, 4, 5, 2, 6, 2, 6, 4, 4, 2, 8, 3, 4, 4, 6, 2, 8, 2, 6, 4, 4, 4, 9, 2, 4, 4, 8, 2, 8, 2, 6, 6, 4, 2, 10, 3, 6, 4, 6, 2, 8, 4, 8, 4, 4, 2, 12, 2, 4, 6, 7, 4, 8, 2, 6, 4, 8, 2, 12, 2, 4, 6, 6, 4, 8, 2, 10, 5, 4, 2, 12, 4, 4, 4, 8, 2, 12, 4, 6, 4, 4, 4, 12, 2, 6, 6, 9]

Raku

Yet more tasks that are tiny variations of each other. Tau function, Tau number, Sum of divisors and Product of divisors all use code with minimal changes. What the heck, post 'em all.

<lang perl6>use Prime::Factor:ver<0.3.0+>; use Lingua::EN::Numbers;

say "\nTau function - first 100:\n", # ID (1..*).map({ +.&divisors })[^100]\ # the task .batch(20)».fmt("%3d").join("\n"); # display formatting

say "\nTau numbers - first 100:\n", # ID (1..*).grep({ $_ %% +.&divisors })[^100]\ # the task .batch(10)».&comma».fmt("%5s").join("\n"); # display formatting

say "\nDivisor sums - first 100:\n", # ID (1..*).map({ [+] .&divisors })[^100]\ # the task .batch(20)».fmt("%4d").join("\n"); # display formatting

say "\nDivisor products - first 100:\n", # ID (1..*).map({ [×] .&divisors })[^100]\ # the task .batch(5)».&comma».fmt("%16s").join("\n"); # display formatting</lang>

Output:
Tau function - first 100:
  1   2   2   3   2   4   2   4   3   4   2   6   2   4   4   5   2   6   2   6
  4   4   2   8   3   4   4   6   2   8   2   6   4   4   4   9   2   4   4   8
  2   8   2   6   6   4   2  10   3   6   4   6   2   8   4   8   4   4   2  12
  2   4   6   7   4   8   2   6   4   8   2  12   2   4   6   6   4   8   2  10
  5   4   2  12   4   4   4   8   2  12   4   6   4   4   4  12   2   6   6   9

Tau numbers - first 100:
    1     2     8     9    12    18    24    36    40    56
   60    72    80    84    88    96   104   108   128   132
  136   152   156   180   184   204   225   228   232   240
  248   252   276   288   296   328   344   348   360   372
  376   384   396   424   441   444   448   450   468   472
  480   488   492   504   516   536   560   564   568   584
  600   612   625   632   636   640   664   672   684   708
  712   720   732   776   792   804   808   824   828   852
  856   864   872   876   880   882   896   904   936   948
  972   996 1,016 1,040 1,044 1,048 1,056 1,068 1,089 1,096

Divisor sums - first 100:
   1    3    4    7    6   12    8   15   13   18   12   28   14   24   24   31   18   39   20   42
  32   36   24   60   31   42   40   56   30   72   32   63   48   54   48   91   38   60   56   90
  42   96   44   84   78   72   48  124   57   93   72   98   54  120   72  120   80   90   60  168
  62   96  104  127   84  144   68  126   96  144   72  195   74  114  124  140   96  168   80  186
 121  126   84  224  108  132  120  180   90  234  112  168  128  144  120  252   98  171  156  217

Divisor products - first 100:
               1                2                3                8                5
              36                7               64               27              100
              11            1,728               13              196              225
           1,024               17            5,832               19            8,000
             441              484               23          331,776              125
             676              729           21,952               29          810,000
              31           32,768            1,089            1,156            1,225
      10,077,696               37            1,444            1,521        2,560,000
              41        3,111,696               43           85,184           91,125
           2,116               47      254,803,968              343          125,000
           2,601          140,608               53        8,503,056            3,025
       9,834,496            3,249            3,364               59   46,656,000,000
              61            3,844          250,047        2,097,152            4,225
      18,974,736               67          314,432            4,761       24,010,000
              71  139,314,069,504               73            5,476          421,875
         438,976            5,929       37,015,056               79    3,276,800,000
          59,049            6,724               83  351,298,031,616            7,225
           7,396            7,569       59,969,536               89  531,441,000,000
           8,281          778,688            8,649            8,836            9,025
 782,757,789,696               97          941,192          970,299    1,000,000,000

REXX

<lang rexx>/*REXX program counts the number of divisors (tau, or sigma_0) up to and including N.*/ parse arg n . /*obtain optional argument from the CL.*/ if n== | n=="," then n= 100 /*Not specified? Then use the default.*/ say 'the number of divisors (tau) for integers up to ' n " (inclusive):"; say say '─index─' center(" tau (number of divisors) ", 80, '─') w= max(7, length(n) ) /*W: used to align 1st output column. */ $= /*$: the output list, shown 20/line. */

               do j=1  for n                    /*list # proper divisors (tau) 1 ──► N */
               $= $  ||  right( tau(j), 4)      /*add a tau number to the output list. */
               if j//20\==0  then iterate       /*Not a multiple of 20?  Don't display.*/
               say center(j-19, 7)  $;  $=      /*display partial list to the terminal.*/
               end   /*j*/

if $\== then say center(j-1, 7) $ /*any residuals left to display ? */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ tau: procedure; parse arg x 1 y /*X and $ are both set from the arg.*/

    if x<6  then return 2 + (x==4) - (x==1)     /*some low #s should be handled special*/
    odd= x // 2                                 /*check if  X  is odd (remainder of 1).*/
    if odd  then do;   #= 2;               end  /*Odd?    Assume divisor count of  2.  */
            else do;   #= 4;   y= x % 2;   end  /*Even?      "      "      "    "  4.  */
                                                /* [↑]  start with known number of divs*/
       do j=3  for x%2-3  by 1+odd  while j<y   /*for odd number,  skip even numbers.  */
       if x//j==0  then do                      /*if no remainder, then found a divisor*/
                        #= # + 2;   y= x % j    /*bump # of divisors;  calculate limit.*/
                        if j>=y  then do;   #= # - 1;   leave;   end   /*reached limit?*/
                        end                     /*                     ___             */
                   else if j*j>x  then leave    /*only divide up to   √ x              */
       end   /*j*/                              /* [↑]  this form of DO loop is faster.*/</lang>
output   when using the default input:
the number of divisors  (tau)  for integers up to  100  (inclusive):

─index─ ─────────────────────────── tau (number of divisors) ───────────────────────────
   1       1   2   2   3   2   4   2   4   3   4   2   6   2   4   4   5   2   6   2   6
  21       4   4   2   8   3   4   4   6   2   8   2   6   4   4   4   9   2   4   4   8
  41       2   8   2   6   6   4   2  10   3   6   4   6   2   8   4   8   4   4   2  12
  61       2   4   6   7   4   8   2   6   4   8   2  12   2   4   6   6   4   8   2  10
  81       5   4   2  12   4   4   4   8   2  12   4   6   4   4   4  12   2   6   6   9

Wren

Library: Wren-math
Library: Wren-fmt

<lang ecmascript>import "/math" for Int import "/fmt" for Fmt

System.print("The tau functions for the first 100 positive integers are:") for (i in 1..100) {

   Fmt.write("$2d  ", Int.divisors(i).count)
   if (i % 20 == 0) System.print()

}</lang>

Output:
The tau functions for the first 100 positive integers are:
 1   2   2   3   2   4   2   4   3   4   2   6   2   4   4   5   2   6   2   6  
 4   4   2   8   3   4   4   6   2   8   2   6   4   4   4   9   2   4   4   8  
 2   8   2   6   6   4   2  10   3   6   4   6   2   8   4   8   4   4   2  12  
 2   4   6   7   4   8   2   6   4   8   2  12   2   4   6   6   4   8   2  10  
 5   4   2  12   4   4   4   8   2  12   4   6   4   4   4  12   2   6   6   9