Enigmatic Code

Programming Enigma Puzzles

Enigma 1552: Prime products

From New Scientist #2715, 4th July 2009 [link]

What are the three different digits that, whichever order you write them down in, form a three-digit integer that is not itself prime but is the product of two primes?

[enigma1552]

Advertisements

2 responses to “Enigma 1552: Prime products

  1. Jim Randell 13 March 2012 at 9:46 am

    Here’s my original Perl solution. It runs in 10ms.

    use strict;
    
    use Enigma qw/factor/;
    
    sub main {
    
      my ($A, $B, $C);
    
      # let's assume $A < $B < $C
      for $A (1..7) {
        for $B ($A+1..8) {
          for $C ($B+1..9) {
            next unless check("$A$B$C");
            next unless check("$A$C$B");
            next unless check("$B$A$C");
            next unless check("$B$C$A");
            next unless check("$C$A$B");
            next unless check("$C$B$A");
            print "A=$A B=$B C=$C\n";
          }
        }
      }
    
    }
    
    sub check {
      my ($n) = @_;
      my @factors = factor($n);
      return unless @factors == 2;
      return 1;
    }
    
    main();
    

    Solution: The digits are 1, 7 and 8.

    • Jim Randell 13 March 2012 at 9:49 am

      This is how I would do it now in Python. It runs in 33ms.

      Python’s combinations() and permutations() iterator functions in the itertools module are perfect for this problem.

      from itertools import combinations, permutations
      from enigma import concat, factor
      
      for s in combinations(range(1, 10), 3):
        if all(len(factor(int(concat(*p)))) == 2 for p in permutations(s)):
          print(sorted(s))
      

Leave a Comment

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: