朝日新聞2005年5月20日パズル横丁解答

プログラムの実行結果は以下の通り。今回は2つの方法の両方をプログラムしてみた。

方法1
  76
× 76
----------
5776

方法2
  76
× 76
----------
5776

プログラムのソースは以下の通り。

#include "puzutl.h"

YesNo used[10];
cstring       ns = "0123456789";

void test1() {
  ps( "方法1\n");
  for( int a=0; a< 10; a++) {
    used[a] = YES;
    for( int b=0; b< 10; b++) {
      if( used[b]) continue;
      used[b] = YES;
      int x = (a*10 + b) * (a*10+b);
      int x1 = x % 10; x /= 10;
      int x2 = x % 10; x /= 10;
      int x3 = x % 10; x /= 10;
      int x4 = x % 10; x /= 10;
      if( x1 == b && x2 == a && x3 == a && (x4 != a && x4 != b)) {
        ps( "  %-.2s%-.2s\n", ns+a*2, ns+b*2);
        ps( "× %-.2s%-.2s\n", ns+a*2, ns+b*2);
        ps( "----------\n");
        ps( "%-.2s%-.2s%-.2s%-.2s\n", ns+x4*2, ns+x3*2, ns+x2*2, ns+x1*2);
      }
      used[b] = NO;
    }
    used[a] = NO;
  }
}

void test2()
{
  ps( "\n方法2\n");
  for( int i=0; i< 100; i++) {
    int j = i;
    int x = i*i;
    int x1 = x % 10; x /= 10;
    int x2 = x % 10; x /= 10;
    int x3 = x % 10; x /= 10;
    int x4 = x % 10; x /= 10;
    int i1 = j % 10; j /= 10;
    int i2 = j % 10; j /= 10;
    if( x2 == i2 && x1 == i1 && x3 == i2 && i1 != i2 && x4 != i1 && x4 != i2) {
      ps( "  %-.2s%-.2s\n", ns+i2*2, ns+i1*2);
      ps( "× %-.2s%-.2s\n", ns+i2*2, ns+i1*2);
      ps( "----------\n");
      ps( "%-.2s%-.2s%-.2s%-.2s\n", ns+x4*2, ns+x3*2, ns+x2*2, ns+x1*2);
    }
  }
}

int main( int argc, cstring argv[])
{
  test1();
  test2();
  return    0;
}