Quote:
The model of computation of Java bytecode is that of a stack-oriented programming language.
Let's see how we can use that with the following Java program for the Prime Factors problem:
package primeFactors;import java.util.*;
public class PrimeFactors {
public static List<Integer> generate(int n) {
List<Integer> primes = new ArrayList<Integer>();for (int candidate = 2; n > 1; candidate++)
for (; n%candidate == 0; n/=candidate)
primes.add(candidate);return primes;
}
}
I used the Java compiler to create a class file and javap to disassemble the code:
javac PrimeFactors.java
javap -c PrimeFactors
That's the result:
Compiled from "PrimeFactors.java"
public class primeFactors.PrimeFactors extends java.lang.Object{
public primeFactors.PrimeFactors();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: returnpublic static java.util.List generate(int);
Code:
0: new #2; //class java/util/ArrayList
3: dup
4: invokespecial #3; //Method java/util/ArrayList."<init>":()V
7: astore_1
8: iconst_2
9: istore_2
10: iload_0
11: iconst_1
12: if_icmple 45
15: iload_0
16: iload_2
17: irem
18: ifne 39
21: aload_1
22: iload_2
23: invokestatic #4; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
26: invokeinterface #5, 2; //InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
31: pop
32: iload_0
33: iload_2
34: idiv
35: istore_0
36: goto 15
39: iinc 2, 1
42: goto 10
45: aload_1
46: areturn}
Now it's straightforward to translate that to RPN:
STO 00 ; int n
2 ; 8: iconst_2
STO 02 ; 9: istore_2
LBL 10
RCL 00 ; 10: iload_0
1 ; 11: iconst_1
X>=Y? ; 12: if_icmple 45
GTO 45
LBL 15
RCL 00 ; 15: iload_0
RCL 02 ; 16: iload_2
MOD ; 17: irem
X#0? ; 18: ifne 39
GTO 39
VIEW 02 ; 22: iload_2
RCL 00 ; 32: iload_0
RCL 02 ; 33: iload_2
/ ; 34: idiv
STO 00 ; 35: istore_0
GTO 15 ; 36: goto 15
LBL 39
1
STO+ 02 ; 39: iinc 2, 1
GTO 10 ; 42: goto 10
LBL 45
RTN ; 46: areturn
We can't return a list and so I decided to just view the factors.
Cheers
Thomas