Write java program to do the following:
 Write a METHOD to input an array of type LONG that stores the value
of all the powers of 2 from 0 to 63 (i.e. 2^0
to 2^63
)
 Output the contents of the array screen (what happens if you try 2^64
?)
 Hint: Math.pow(x,y) is used to put number x to exponent y

Program just outputs 1.0 many times which isn't right can anyone help

public class W3P3{
    public static void main(String[]args){
        double [] myArray = new double [63];
        long myEntry=0;
        long Myarray=0;
            power(myEntry,Myarray);


    }//end of main
    //Method
    public static void power(long x,long y){
    double results=0;
    for (int i = 2; i <= 63; i++)
    {
    results = Math.pow(x,y);
    System.out.println("The result of powers is "+ results);
    }
    }//end of method
}//end of class

Recommended Answers

All 4 Replies

You pass two values (x,y) into your method. You then have a loop with values of i 2..63, but you do not use i anywhere in your loop. Instead of pow(x,y) you need to raise 2 to the power i

You can make use of the left shift operator: <<.

2^2 = 2 << 1
2^3 = 2 << 2
2^4 = 2 << 3
etc.

It works as follows: the decimal number 2 can be represented in binary as 00000010.
The << operator shifts all the bits to the left by the number of positions specified by its right operand. So:

  Java  |                 |  Binary outcome  |  Decimal  |  2^n
------------------------------------------------------------------
 2 << 1 |  00000010 << 1  |    00000100      |     4     |  2^2
 2 << 2 |  00000010 << 2  |    00001000      |     8     |  2^3
 2 << 3 |  00000010 << 3  |    00010000      |    16     |  2^4

Edit: This will cause overflow for large n, highest power I was able to get without overflowing, is: 2^62 using long.

It's ok I think I have it thanks JamesCherrill and mv malderen :D

public class W3P3{
    public static void main(String[]args){
        long [] myArray = new long [63];
        long myEntry=2;
        long Myarray=0;
            power(myEntry,Myarray);


    }//end of main
    //Method
    public static void power(long x,long y){
    double results=0;
    for (int i = 0; i < 63; i++)
    {
    results = Math.pow(x,i);
    System.out.println("The result of powers is "+ results);
    }
    }//end of method
}//end of class

Just one more thing how do I change the i < 63; to something using the Array such as x.length; or something along the lines

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.