Triangular Phun

23 05 2019


Photo on Flickr by Larkspur Studio

Some academic questions are simply too fun, i.e. phun in old-style PHP lingo, to shun. Mixing prime numbers with triangles may seem like a wacky idea, but once you’ve tried it, you may find yourself completely captivated.

Recently, I chanced upon an entertaining question concerning how to display prime numbers in the shape of a right-angled triangle using PHP. The question has two aspects, understanding the nature of prime numbers and knowing how to programatically generate a triangle shape. One may define prime numbers as whole numbers greater than one, but divisible only by one and their own value (source: techtarget.com.) With this basis, one may devise an appropriate algorithm for generating a range of such numbers. Then, one must figure out how to put them into the specified triangle.

The Right Angle

The following example illustrates one solution that produces a right triangle, as follows:

<?php
function isPrimeNumber($num) {
   $isPrime = 1;
   for ($i = 2; $i <= ($num/2); $i++) {
      if ($num % $i == 0){
         $isPrime = 0;
         break;
      }
   }
   return ($isPrime==1 || $num==2)? 1 : 0;
}

function generateRightTriangle( $rows ) { 
define("START",2);   
  for ($i = 1, $count = START; $i <= $rows; $i++) {
      for ($j = 1; $j <= $i; $j++) {
         while( !isPrimeNumber($count) ){
            $count++;
         }
         printf(" %-2d", $count);
         $count++;
      }
      printf("\n");
  }
  return true;
}
if (!generateRightTriangle(5)) {
    trigger_error("An error has occurred!");
}

See live code

When run, the code displays five rows of prime numbers, with the first line bearing one number and each successive line has a quantity of numbers corresponding to the line number, thereby producing the triangle.

I took a short-cut for this exercise by finding code in another language familiar to me and then translated it into PHP.  I borrowed heavily from here and also here. Since the source code of is in the C Programming Language, I  prepended all  variables with the characteristic sigil, namely the dollar-sign, which signifies a PHP variable while ignoring  code pertaining to variable declarations and any other features that PHP does not require.

Although the translated code executed fine, an issue might have arisen with its reliance on global variables, especially if one uses NetBeans 8.2.  Also, using global variables is not a best PHP practice. Globals in PHP can create buggy, problematic code, so using such variables is strongly discouraged. In fact, I’d go so far to say that global variables are virtual pariahs in PHPland. so, I refactored the code and now it contains two functions and all variables are local to one function or the other.

The Inverse

If you want a more interesting challenge consider displaying the data in an inverse right triangle.  The remedy essentially involves tailoring the above code, specifically the function generateRightTriangle((), as follows:

<?php
[..snip..]
function generateRightTriangle( $rows ) {
define("END", 47);    
for ($i = 1, $count = END; $i = $i; $j--) {
         while( !isPrimeNumber($count) ){
            $count--;
         }
         if ($count == 3) {
            printf("%2d",$count);
         }
         else
                   {
          printf("%d ",$count);
         }
         $count--;
      }
      printf("\n");
}
return true;
}
if (!generateRightTriangle(5)) {
    trigger_error("An error has occurred!");
}

See live code

Reverse Right Triangle

Emboldened by the preceding successful outcomes, I considered a  more daunting, challenge, how to generate a reverse right triangle, filling it with the designated data.  The best way to approach this problem is to focus on the necessary blank space and then modify generateRightTriangle() accordingly. The following code, the result of seemingly endless tinkering and rethinking, may be less than aesthetically pleasing but it does deliver:

<?php
[..snip..]
function generateRightTriangle( $num ) {
for ($i = 1, $rows = $num, $count = 2; $i <= $rows; $i++) {
      /* Print spaces in decreasing order of row */
      for($j=$i; $j < $rows; $j++)
      {
          printf("%s","   ");
      }
      for ($j = 1; $j <= $i; $j++) {
         while( !isPrimeNumber($count) ){
            $count++;
         }
         if ($i == 1) {
          printf("  %d",$count);
         }
         else
         if ($i == 2) {
          printf("  %-d",$count);
         }
         else
         if ($i == 3) {
          if ($count == 7) {
                printf("  %-d",$count);
          }
          else
          {
          printf(" %-2d",$count);
          }
         }
         else
         {
         printf(" %-d", $count);
         }
         $count++;
      }
      printf("\n");
}
return true;
}

if (!generateRightTriangle(5)) {
    trigger_error("An error has occurred!");
}}

See live code

This example utilizes printf() with both left and right justification as well as field width specifiers to achieve the desired result.

Recommended Reading

This work is licensed under a Creative Commons License

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.




%d bloggers like this: