68 lines
1.8 KiB
Text
68 lines
1.8 KiB
Text
.class public Factorial
|
|
.super java/lang/Object
|
|
|
|
.method public <init>()V
|
|
aload 0
|
|
invokenonvirtual java/lang/Object/<init>()V
|
|
return
|
|
.end method
|
|
|
|
.method public static factorial(I)I ; calc `given`!
|
|
.limit locals 3
|
|
.limit stack 2
|
|
; note that parameters are automatically stored as
|
|
; local variables, we dont need to do `istore 0` to
|
|
; store the given integer in a local variable.
|
|
bipush 1 ; we start calculating with `p`=1
|
|
istore 1 ; store `p`
|
|
bipush 2 ; we start calculating with `j`=1
|
|
istore 2 ; store `j`
|
|
loop:
|
|
; p *= j
|
|
iload 1 ; load p
|
|
iload 2 ; load j
|
|
imul ; multiply p and j
|
|
istore 1 ; store p*j in p
|
|
|
|
; j++
|
|
iload 2 ; load j
|
|
bipush 1 ; put a 1 on the stack
|
|
iadd ; add j and 1
|
|
istore 2 ; store j+1 in j
|
|
|
|
; if j<given
|
|
iload 2 ; load j
|
|
iload 0 ; load given
|
|
if_icmplt loop ; if j < given goto loop
|
|
|
|
; else return given * p
|
|
iload 0 ; load given
|
|
iload 1 ; load p
|
|
imul ; multiply given and p
|
|
|
|
ireturn ; return given*p
|
|
.end method
|
|
|
|
.method public static main([Ljava/lang/String;)V
|
|
.limit locals 3
|
|
.limit stack 4
|
|
; parse cli args to int
|
|
aload 0
|
|
aaload 0
|
|
invokestatic java/lang/Integer/parseInt(Ljava/lang/String;)I
|
|
istore 1
|
|
|
|
; format
|
|
iload 1
|
|
ldc "! = "
|
|
iload 1
|
|
invokestatic Factorial/factorial(I)I ; call factorial
|
|
invokevirtual java/lang/String/format(ILjava/lang/String;I)I
|
|
astore 2
|
|
|
|
; output
|
|
getstatic java/lang/System/out Ljava/io/PrintStream;
|
|
aload 2 ; load formatted str
|
|
invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
|
|
return
|
|
.end method
|