-1

Whenever I run the program, input 2 for x 2 for y it will result 4 which is fine, but whenever I put in 2 to power of 3 it outputs 9 when it should output 8 and when I do 3 to power of 2 it outputs 8 when it should give 9. It works for 2^2, 2^4 but not for 2^3. Also 8^8 gives 256. Is the program written wrong?

/ Start of the main program 
Input / Enter the exponent Store y
Subt One
Store Count

Input / Enter the Base
Store x
Store y
Jns Exp

/ Ending the main program
Load Ans 
Output 
End, Halt

Exp, Hex 0
Loop2, Load Count
    Skipcond 800
    JumpI Exp
    JnS Multiplier
    Load Ans
    Store x
    Load Count
    Subt One
    Store Count
    Jump Loop2

/ Start of the subroutine Multiplier
Multiplier, Hex 0
    Load Zero
    Store Ans
Loop, Load x
    Skipcond 800
    JumpI Multiplier
    Load Ans
    Add y
    Store Ans
    Load x
    Subt One
    Store x
    Jump Loop

/ Declaration
x, Dec 2
y, Dec 3
Zero, Dec 0
One, Dec 1 
Ans, Dec 0 
Count, Dec 0

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Dave
  • 1
  • 1
  • 9
  • 38
  • Have you considered that 2^4 == 4^2 and you simply are calculating a^b instead of b^a? For 8^8, which fits 32 bits, but doesn't fit 16 I can't imagine a source of overflow -- except that you are returning the high 16 bits. – Aki Suihkonen May 18 '21 at 14:27

1 Answers1

2

You've got the arguments backwards. Your results for 2**3 and 3**2 are simply backwards. 2**2 and 2**4 aren't affected by the order of arguments.

It's not possible to represent 8**8 with 16-bit numbers, since that's 0x1000000, so you'll always get the wrong result.

Your code takes the exponent first, then the base.


I use the ** convention for exponent instead of ^, because the latter is used to denote an exclusive-or in most programming languages.

Thomas Jager
  • 4,836
  • 2
  • 16
  • 30
  • But why are the results backwards? Is is something wrong with the code or? – Dave May 18 '21 at 16:50
  • The results aren't backwards at all. You're giving them in the wrong order. The first argument is the exponent, then the base. Read the code you provided, it asks for the exponent first. When you do `x**y`, you first type in `y`, then you type in `x`. This could be changed (not that it's wrong now, just different) by swapping the first sets of inputs and stores. – Thomas Jager May 18 '21 at 17:24