[Challenge] Print Times Tables šŸ–ØāŽ

Python 3 code: https://repl.it/LLq4/2

def timesTables(skip=1):
  # in every line n of the times table...
  for n in range(1, 13, skip):
    # ... the products start from n and increase by n
    for product in range(n, 12*n+1, n*skip):
      print(product, end=' ')
    print()

def oddTimesTables():
    timesTables(skip=2)

The code is explained in the comments (as much as there is to explain). It is based on the observation that each product at line n differs by its previous one by n.

Hi, here is my code with comments
https://repl.it/LLwz/0

Saludos

This is what i did in C

#include <stdio.h>

void timesTables(void)
{
	int x, y, array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

	for(x=1; x<=12; x=x+1)
	{
		for(y=0; y<=11; y=y+1)
		{
			printf("%d ", array[y]*x);
		}
		printf("\n");
	}
}

int main(void)
{
	timesTables();
	
	return 0;
}

Basic and Intermediate
JavaScript

Code: https://repl.it/LRYp/1

Commented in the code.

Basic Level in Python

def timesTables():
  a = range(1,13)
  c = 1
  while c<13:
    for x in a:
      print c*x,
    c+=1
    print ''
  return
     
timesTables()

Output:

1 2 3 4 5 6 7 8 9 10 11 12 
2 4 6 8 10 12 14 16 18 20 22 24 
3 6 9 12 15 18 21 24 27 30 33 36 
4 8 12 16 20 24 28 32 36 40 44 48 
5 10 15 20 25 30 35 40 45 50 55 60 
6 12 18 24 30 36 42 48 54 60 66 72 
7 14 21 28 35 42 49 56 63 70 77 84 
8 16 24 32 40 48 56 64 72 80 88 96 
9 18 27 36 45 54 63 72 81 90 99 108 
10 20 30 40 50 60 70 80 90 100 110 120 
11 22 33 44 55 66 77 88 99 110 121 132 
12 24 36 48 60 72 84 96 108 120 132 144 

The function creates a counter variable and an array with a given length, and the uses ā€œwhileā€ loop to print values in the array mutiplied by the accumulative counter.

https://repl.it/LWNo/12

1 Like

Intermediate Difficulty in Python

def oddTimesTables():
  a = range(1,13,2)
  for x in a:
    for y in a:
      print x*y,
    print ''
  return
      
oddTimesTables()

Output:


1 3 5 7 9 11 
3 9 15 21 27 33 
5 15 25 35 45 55 
7 21 35 49 63 77 
9 27 45 63 81 99 
11 33 55 77 99 121 

The function creates a range of odd values from 1 to 12 and uses nested loop to multiply these values.
[Edited to take into account the comments]

https://repl.it/LWRI/12

1 Like

2 posts were split to a new topic: Why use modulo?

Hereā€™s my solution with explanation (using Python): https://repl.it/LWzv/0

C++ submission here: https://repl.it/LThu/19

Since the definition of ā€˜efficiencyā€™ is rather vague and a naive implementation is basically as fast as the function possibly could be, I instead decided to interpret ā€˜efficiencyā€™ as if I were programming a more complicated mathematical table on an old CPU where memory accesses are cheap and mathematical operations (i.e. multiplications) are expensive. Therefore, my ā€˜efficientā€™ implementation of timesTables performs the minimum required number of multiplications (i.e. the upper-triangular portion of the table), stores the result, and prints the full table from this ā€˜compressedā€™ list of numbers. The total number of multiplications performed is therefore (N^2 + N)/2 instead of N^2, with in increase in ā€˜efficiencyā€™ by a factor of nearly 2 for large N.

If we want to define efficiency by minimizing the number of multiplications performed then I offer up this for your consideration:

def printTable(last, odds=False):
    if odds:
        numbers = range(1,last+1,2)
    else:
        numbers = range(1,last+1)
    for i in numbers:
        p = i
        for j in numbers:
            print('{:>4}'.format(p),end="")
            p += i
            if odds:
                p += i
        print()

def timesTables():
    printTable(12)

def oddTimesTables():
    printTable(12, odds=True)

timesTables()
print()
oddTimesTables()

Here is the output, same as before:

   1   2   3   4   5   6   7   8   9  10  11  12
   2   4   6   8  10  12  14  16  18  20  22  24
   3   6   9  12  15  18  21  24  27  30  33  36
   4   8  12  16  20  24  28  32  36  40  44  48
   5  10  15  20  25  30  35  40  45  50  55  60
   6  12  18  24  30  36  42  48  54  60  66  72
   7  14  21  28  35  42  49  56  63  70  77  84
   8  16  24  32  40  48  56  64  72  80  88  96
   9  18  27  36  45  54  63  72  81  90  99 108
  10  20  30  40  50  60  70  80  90 100 110 120
  11  22  33  44  55  66  77  88  99 110 121 132
  12  24  36  48  60  72  84  96 108 120 132 144

   1   3   5   7   9  11
   3   9  15  21  27  33
   5  15  25  35  45  55
   7  21  35  49  63  77
   9  27  45  63  81  99
  11  33  55  77  99 121

And the link: https://repl.it/LEFg/11

1 Like

Hereā€™s my code:
https://repl.it/LZjo/2

I commented most lines, hope you like my first entry :smiley:

Hereā€™s my code. It is well commented
https://repl.it/L2LL/3

Hi,

Hereā€™s a try with python and numpy : https://repl.it/L4rN/2

The main idea is :

import numpy as np

def makeLine(mult, maxi, step):
    return np.arange(mult, mult * maxi + 1, step)

def makeLines(maxi = 12):
    return [makeLine(x, maxi, x) for x in range(1, maxi + 1)]

times = np.array(makeLines())
print(times)

As numpyā€™s arrays/matrix are known to be faster than loops, I think it should worth the cost of extra square brackets.

The second try uses the symmetry of the table to minimize the number of computations : less than 80 for a 12x12 table.

@star3lord @cloudrunner15916 Thanks for the comments, they certainly helped to make the code more concise!

Hard Difficulty:


Elegant, minimal approach that will be better explained if I show you the uncompressed version,

ls = [i * j for i in range(1,13) for j in range(1,13)]
chunks = [print(ls[x:x+12]) for x in range(0, len(ls), 12)]

Uncompressed Version:

#create an empty list
ls = []
#create multiplication table using nested loops
for i in range(1,13):
    for j in range(1,13):
        ls.append(i*j)
#split the table at every 12th index and print it out
for x in range(0,len(ls),12):
        print(ls[x:x+12])

https://repl.it/Lczq

2 Likes

It took me a couple of evenings, a lunch break and some help from a friend to get this, but it was fun and frustrating.
Iā€™d really appreciate any advice or corrections that I could make also as Iā€™m learning Javascript.
Iā€™m guessing that console.log(); isnā€™t really an output, but thatā€™s all I know for now!

This is my Javascript code (basic difficulty)

for (let i = 0; i < 12; i++) {
  let timesTables = '';
  for (let j = 0; j < 12; j++) {
    if (j === 11) {
      timesTables = timesTables + (j + 1) * (i + 1);
    } else {
      timesTables = timesTables + (j + 1) * (i + 1) + ' '; //initially I set it up using commas so this is currently redundant.
    }
  }
  console.log(timesTables);
}

This is my submission to the Basic difficulty it didnā€™t take me long but I made it as efficient as I could and it explains itself through comments.
Itā€™s in the swift coding language
Hereā€™s the link: https://repl.it/NZaI/0
And the code:

// these goes up every time times tables is called
var c1 = 1
var c2 = 1
//the function that happens to make the tables show
func timesTables() {
    //prints c1 times c2 before it adds more numbers to make it show 1*1 too
     print(c1*c2)
    if c2 == 12 {
        c1 += 1
        c2 = 1
    } else if c2 < 12 {
        c2 += 1
    }
}
//this runs it until the code has printed all the numbers (144 to be exact)
while c1 != 13 {
    timesTables()
}

Intermediate difficulty using JavaScript:
https://repl.it/@Dunjamarc/JointLuckyAzurevasesponge
Explanation provided with code.

Intermediate difficulty using JavaScript.
Comments are included in the code.
https://repl.it/@supermonkey42/printTimesTableschallenge

The program uses two for loops to loop through two variables, i and j. i starts out at 1; j loops from 1 to 12, multiplying by i each time, checking the result to see if it is odd, and adding it to an array. Then the array is logged to the console and cleared, then i increments by 1 and the process repeats. It will repeat until i = 12.

//Generates a multiplication table but leaves out all even numbers.

//Set variables.
var timesNum = 0;
var numArray = [];


function oddTimesTables() {
  /*Use two for loops. Increment j from 1 to 12, multiplying by i each time, 
  checking to see if the result is odd, and adding it to an array, then 
  increment i once and repeat. Repeat until i = 12. */
  for(i=1; i<=12; i++) {
    for(j=1; j<=12; j++) {
      timesNum = j*i;
      //Check to see if timesNum is odd. If it is, it is added to numArray.
      if(timesNum % 2 !== 0) {
        numArray.push(timesNum);
      }
    }
    //Log a line of numbers to the console.
    console.log(numArray);
    //Clear the array.
    numArray = [];
  }
}

oddTimesTables();
def oddTimesTables():
	for i in range(1,13):
		temp = ""
		for j in range(1,13):
			temp = temp + str(i*j) + " "
		print(temp)
	return 
oddTimesTables()