Program to solve the Problem of the Week

for the week of April 9, 2001
by Richard Johnson


/*
// 45678.cpp
//
// A test program to return 2 numbers
// such that their difference is 45,678
// with unique digits 0 - 9
*/


#include <iostream>

using namespace std;

const int N_MAX = 98765;
const int N_MIN = 45678 + 1234;

bool IsAnswer(int n);
// Pre: N_MIN <= n <= N_MAX
// Post: return true if n and 
// n - 45678 contain unique digits
// 0,1,2,3,4,5,6,7,8,9

int main()
{
 for (int i=N_MIN; i <=N_MAX; i++)
  if (IsAnswer(i))
   cout << i << "   " << i - 45678 << endl;

 return 0;
}

bool IsAnswer(int n)
// Pre: N_MIN <= n <= N_MAX
// Post: return true if n and 
// n - 45678 contain unique digits
// 0,1,2,3,4,5,6,7,8,9
{
 int s = n - 45678;

 int nDigit1 = n / 10000;
 int sDigit1 = s / 10000;

 if (nDigit1 == sDigit1)
  return false;

 int nDigit2 = n % 10000 / 1000;
 int sDigit2 = s % 10000 / 1000;

 if (nDigit2 == sDigit2 ||
  nDigit2 == nDigit1 || 
  sDigit2 == sDigit1 ||
  nDigit2 == sDigit1 || 
  sDigit2 == nDigit1)
  return false;

 int nDigit3 = n % 1000 / 100;
 int sDigit3 = s % 1000 / 100;

 if (nDigit3 == sDigit3 ||
  nDigit3 == nDigit2 || 
  sDigit3 == sDigit2 ||
  nDigit3 == nDigit1 || 
  sDigit3 == sDigit1 ||
  nDigit3 == sDigit2 || 
  sDigit3 == nDigit2 ||
  nDigit3 == sDigit1 || 
  sDigit3 == nDigit1)
  return false;

 int nDigit4 = n % 100 / 10;
 int sDigit4 = s % 100 / 10;

 if (nDigit4 == sDigit4 ||
  nDigit4 == nDigit3 ||  
  sDigit4 == sDigit3 ||
  nDigit4 == nDigit2 || 
  sDigit4 == sDigit2 ||
  nDigit4 == nDigit1 || 
  sDigit4 == sDigit1 ||
  nDigit4 == sDigit3 || 
  sDigit4 == nDigit3 ||
  nDigit4 == sDigit2 || 
  sDigit4 == nDigit2 ||
  nDigit4 == sDigit1 || 
  sDigit4 == nDigit1)
  return false;

 int nDigit5 = n % 10;
 int sDigit5 = s % 10;

 if (nDigit5 == sDigit5 ||
  nDigit5 == nDigit4 || 
  sDigit5 == sDigit4 ||
  nDigit5 == nDigit3 || 
  sDigit5 == sDigit3 ||
  nDigit5 == nDigit2 || 
  sDigit5 == sDigit2 ||
  nDigit5 == nDigit1 || 
  sDigit5 == sDigit1 ||
  nDigit5 == sDigit4 || 
  sDigit5 == nDigit4 ||
  nDigit5 == sDigit3 || 
  sDigit5 == nDigit3 ||
  nDigit5 == sDigit2 || 
  sDigit5 == nDigit2 ||
  nDigit5 == sDigit1 || 
  sDigit5 == nDigit1)
  return false;

 return true;
}