Robson » Little Red Book » Triadic numbers

Chapter 6 - Question 7

The nine digits 1, 2, 3, 4, 5, 6, 7, 8 and 9 can be re-arranged in a very large number of ways. If an arrangement of these nine digits was taken and considered as three groups of three digits then each group of three digits could be thought of a normal decimal number.

A triadic sequence is a sequence of three numbers such that the second is twice the first and the third is three times the first - i.e. of the form, N, 2*N, 3*N.

Produce a program to find all the triadic sequences that can be formed using each of the digits 1 - 9 once and once only.

Solution 1

Here's my dodgy C++ solution:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
 
int main()
{
   int t[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
   char* cd = new char[10];    
   bool bValid;
   int a, b, c;    
   for (int n = 123456789; n < 340000000; n++)
   {
          bValid = true;
          itoa(n, cd, 10);  
          for(int i = 0; i <= 9; i++)
              t[i] = 0;          
          for(int i = 0; i < 9; i++)
              t[cd[i]-48]++;
          if (t[0])
             bValid = false;
          for(int i = 9; i > 0; i--)
          {
              if (t[i] != 1)
              {
                 bValid = false;
                 break;
              }
          }
          if (bValid)
          {
              a = ((cd[0]-48) * 100) + ((cd[1]-48) * 10) + (cd[2]-48);
              b = ((cd[3]-48) * 100) + ((cd[4]-48) * 10) + (cd[5]-48);
              if (b == a * 2)
              {
                  c = ((cd[6]-48) * 100) + ((cd[7]-48) * 10) + (cd[8]-48);    
                  if (c == a * 3)
                     printf("{%d,%d,%d}\n", a, b, c);
              }
          }
   }        
   return 0;
}
 

Which produces:

{192,384,576}
{219,438,657}
{273,546,819}
{327,654,981}

Log

© 2004-17 robson | cc unless stated