Back to DFS's Workshop Page
Back to Agenda Page
Odd Numbers With Unique Digits
An Array Problem
Determine the number of odd numbers between 5000 and 8000 in which all of the digits are different.
It is suggested that you use a for loop to generate all of the numbers. Inside the loop, you can follow the pseudocode below.
- Convert the integer value to a string using sprintf() so each digit can be checked
- Initialize an array of flags to keep track of which digits are found in the number. You can use either of two data types for the subscripts:
- Integer values from 0 to 9 (this would require later conversion of the digit from a char to an integer -- ord(charvalue) - 48).
- Char values from '0' to '9' (this permits the direct use of the character in the string as the subscript).
- Set a flag in the array for each digit found.
- Count the number of unique digits -- the ones flagged in the array.
- Increment a counter if the number is odd and has four unique digits.
To check what is in the array of flags while you are developing your code, you can use the built-in function print_r().
To see how this could work, view this possible solution, which also provides the answer to the problem.
The non-brute force method of solving this problem would be as follows:
1 x 8 x 7 x 4 = 224 for 5000s
1 x 8 x 7 x 5 = 280 for 6000s
1 x 8 x 7 x 4 = 224 for 7000s
This yields a total of 728 odd numbers which have no duplication of digits.
© 2004 DFStermole
Created 7 July 04
Last Modified 8 July 04