How to print exponents in 4x4x4 = 64 form in Java

Viewed 126

I have created a java program which calculate the exponent(power) of a number. The program is working fine but I want to know how to print the result in this form nxnxn = n.

Below is my program

long number=3;
long exponent=4;
long result=number;
for (int i=1;i<exponent;i++)
{
    result=result*number;

    System.out.println(number +" x " + number + " = " +result);
}
5 Answers

You can store this value(NxNxN...) in a String

StringBuilder str = new StringBuilder(number+"");
for (int i=1; i<exponent; i++) {
    str.append("x").append(number);
    result = result * number;
}
System.out.println(str + " = " + result);

I would just simply create n element list with exponent times repeated number and then join it to string

List<Integer> list = Collections.nCopies(exponent, number);
String resultString = String.join("x", list) + " = " + result;
System.out.println(resultString);

You can also create new array and use Arrays.fill() method

To print strings in one line you need to use System.out.print() instead of System.out.println().

Also you need to move the output of the result out of the loop and print the multiplication sign only if it is not the last multiplication

long number = 4;
long exponent = 3;
long result = 1;
for(int i = 0; i < exponent; i++) {
    result = result * number;

    System.out.print(number);
    if(i < exponent - 1) {
        System.out.print(" x ");
    }
}
System.out.println(" = " + result);

Output

4 x 4 x 4 = 64

Since the number can get kinda long, why don't you save it in a StringBuilder? or even a string then add them each time in the loop in the end print the result outside the loop as follows

String equationStr = "";
long number=3;
long exponent=4;
long result=number;
for (int i=1;i<exponent;i++)
{
    result=result*number;
    if(i < exponent - 1)
        equationStr += result + "×";
    else
        equationStr += String.valueOf(number);

    
}

System.out.println(equationStr + " = " + result);

Try this.

public static void main(String[] args) {
    long number = 4;
    long exponent = 3;
    System.out.println(number + (" x " + number).repeat((int) exponent - 1)
        + " = " + (int) Math.pow(number, exponent));
}

output:

4 x 4 x 4 = 64
Related