RPN: HP 15C and DM32: Integer Length and Digit Extraction (up to 99,999,999)
The following programs are utilities for positive integers:
(1) Integer Length: how many digits in a positive integer
(2) Digit Extraction: Get the nth digit of a positive integer
Note: Do not use more than 8 digits (integers up to 99,999,999). Beyond this, the program may return inaccurate answers.
Thanks to J-F Garnier for pointing out the limitation of the programs.
Integer Length
Find the number of digits of a positive integer. The integer is decimal base (base 10).
For a positive integer n, the number of the digits can be easily found by the formula:
L = int(log(x)) + 1
DM32, HP 32S, HP 32SII Code
L01 LBL L
L02 LOG
L03 IP
L04 1
L05 +
L06 RTN
HP 15C, DM15 Code
001 |
42, 21, 11 |
LBL A |
002 |
43, 13 |
LOG |
003 |
43, 44 |
INT |
004 |
1 |
1 |
005 |
40 |
+ |
006 |
43, 32 |
RTN |
The program finds the number of digits in the positive integer in the X stack.
Examples:
X = 436782; Length: 6
X = 5195008; Length: 7
X = 23156956; Length: 8
Digit Extraction
Extract the nth digit of a positive integer. Digit positions go from left to right. For example: for the integer 4582, the 1st digit is 4, the 2nd digit is 5, 3rd digit is 8, and 4th digit is 2.
Steps that this program follows:
Step 1: Find the length of the positive integer. L = int(log(x)) + 1.
Step 2: Divide X by 10^(L – n + 1). D = X / (10^(L – n + 1))
Step 3: Extract the fractional part. D = frac(D)
Step 4: Multiple the result by 10 and extract the integer part. D = int(10 * D)
Setting up the stack:
Y: integer
X: nth digit to extract
Variables Used:
DM32, HP 32S, HP 32S II |
HP 15C, DM15 |
X |
R1 |
N |
R2 |
L |
R3 |
DM32, HP 32S, HP 32SII Code
E01 LBL E
E02 STO N
E03 R↓
E04 STO X
E05 LOG
E06 IP
E07 1
E08 +
E09 STO L
E10 RCL X
E11 RCL L
E12 RCL- N
E13 1
E14 +
E15 10^x
E16 ÷
E17 FP
E18 10
E19 ×
E20 IP
E21 RTN
HP 15C, DM15 Code
001 |
42, 21, 12 |
LBL B |
002 |
44, 2 |
STO 2 |
003 |
33 |
R↓ |
004 |
44, 1 |
STO 1 |
005 |
43, 13 |
LOG |
006 |
43, 44 |
INT |
007 |
1 |
1 |
008 |
40 |
+ |
009 |
44, 3 |
STO 3 |
010 |
45, 1 |
RCL 1 |
011 |
45, 3 |
RCL 3 |
012 |
45, 30, 2 |
RCL- 2 |
013 |
1 |
1 |
014 |
40 |
+ |
015 |
13 |
10^x |
016 |
10 |
÷ |
017 |
42, 44 |
FRAC |
018 |
1 |
1 |
019 |
0 |
0 |
020 |
20 |
× |
021 |
43, 44 |
INT |
022 |
43, 32 |
RTN |
Examples
Integers |
Length |
2nd Digit |
4th Digit |
5th Digit |
436782 |
6 |
3 |
7 |
8 |
5195008 |
7 |
1 |
5 |
0 |
23156956 |
8 |
3 |
5 |
6 |
Eddie
All original content copyright, © 2011-2025. Edward Shore. Unauthorized use and/or unauthorized distribution for commercial purposes without express and written permission from the author is strictly prohibited. This blog entry may be distributed for noncommercial purposes, provided that full credit is given to the author.
All posts are 100% generated by human effort. The author does not use AI engines and never will.