Tried all the ways to pass the test case but it still shows only one error. I do not know how to rectify the error.
Input: 1534236469
Actual Output: 1056389759
Expected Output: 0
I do not know why my code does not give output 0.
class Solution
{
public static int reverse(int x)
{
boolean flag = false;
if (x < 0)
{
x = 0 - x;
flag = true;
}
int res = 0;
int p = x;
while (p > 0)
{
int mod = p % 10;
p = p / 10;
res = res * 10 + mod;
}
if (res > Integer.MAX_VALUE)
{
return 0;
}
if (flag)
{
res = 0 - res;
}
return res;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int revinteger = reverse(x);
System.out.println(revinteger);
}
}
The statement res > Integer.MAX_VALUE will never be true as res is of int datatype. And an int can never be larger than the Integer.MAX_VALUE (MAX_VALUE is itself the max we can store as int).
Use long datatype for reversing the number instead and at the end return the integer value of the result.
Because long based operations are relatively slow, I would only use a long to do the final check to determine if overflow is about to occur.
It should be obvious that no int will cause overflow if all the digits except the last are reversed. So process the last digit outside of the loop before returning the value. The border case for min is eliminated first to facilitate subsequent processing. Now only Integer.MAX_VALUE is of concern for both positive and negative numbers.
public static int reverse(int v) {
if (v == Integer.MIN_VALUE) {
return 0; // guaranteed overflow if reversed.
}
int rev = 0;
long ovflLimit = Integer.MAX_VALUE;
int sign = v < 0 ? -1 : 1;
v *=sign;
while (v > 9) {
int digit = v % 10;
rev = rev * 10 + digit;
v/=10;
}
long ovfl = (long)(rev)*10+v;
return ovfl > ovflLimit ? 0 : (int)(ovfl)*sign;
}
This problem can be solved in various ways but if we stick to Java and your solution then as it already have been pointed out in some of the answers that by using int the condition if(res > Integer.MAX_VALUE) will never be true.
Hence you would not get expected output as 0.
You can put a check before reversing last digit by casting the value in long and check if it's out of int limit. As suggested by WJS.
In case you want to stick to your solution without much change below is the working code for the same.
class Solution {
public static int reverse(int x) {
boolean flag = false;
long input = x;
if (input < 0) {
input = 0 - input;
flag = true;
}
long res = 0;
long p = input;
while (p > 0) {
long mod = p % 10;
p = p / 10;
res = res * 10 + mod;
}
if (res > Integer.MAX_VALUE) {
return 0;
}
if (flag) {
res = 0 - res;
}
return (int) res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int revInteger = reverse(x);
System.out.println(revInteger);
}
}
if (res > Integer.MAX_VALUE)
If it's the max possible value of the integer, how will it ever be greater than it? You'll have to detect it in another way.
One way would be to use the long data type instead of int. Then, it can become larger than Integer.MAX_VALUE, and that catch will work.
Otherwise, you can probably find another way to catch that case.
Related
I wrote a simple program to calculate the maximum number of times square root can be calculated on a number , input is an interval from num1 to num2
eg:
if the input is (1,20), answer is 2, since square root of 16 is 4 , and square root of 4 is 2 .
int max = 0;
for (int i = num1; i <= num2; i++) {
boolean loop = true;
int count = 0;
int current = i;
if (i == 1) {
count++;
} else {
while (loop) {
double squareRoot = Math.sqrt(current);
if (isCurrentNumberPerfectSquare(squareRoot)) {
count++;
current = (int) squareRoot;
} else {
loop = false;
}
}
}
if (count > max) {
max = count;
}
}
return max;
static boolean isCurrentNumberPerfectSquare(double number) {
return ((number - floor(number)) == 0);
}
I get the answer, but was wondering wether this can be improved using some mathematical way ?
Any suggestions ?
To avoid more confusion here my final answer to this topic.
A combination of both previously mentioned approaches.
What 'Parameswar' is looking for is the largest perfect square formed by the lowest base.
Step 1 -
To get that calculate the largest possible perfect square based on your num2 value.
If it is outside your range, you have no perfect square within.
Step 2 -
If it is within your range, you have to check all perfect square formed by a lower base value with a higher number of times.
Step 3 -
If you find one that is within your range, replace your result with the new result and proceed to check lower values. (go back to Step 2)
Step 4 -
Once the value you check is <= 2 you have already found the answer.
Here some sample implementation:
static class Result {
int base;
int times;
}
static boolean isCurrentNumberPerfectSquare(double number) {
return ((number - Math.floor(number)) == 0);
}
private static int perfectSquare(int base, int times) {
int value = base;
for (int i = times; i > 0; i--) {
value = (int) Math.pow(base, 2);
}
return value;
}
private static Result calculatePerfectSquare(int perfectSquare) {
Result result = new Result();
result.base = (int) Math.sqrt(perfectSquare);
result.times = 1;
while (result.base > 2 && isCurrentNumberPerfectSquare(Math.sqrt(result.base))) {
result.base = (int) Math.sqrt(result.base);
result.times += 1;
}
System.out.println(perfectSquare + " -> " + result.base + " ^ " + result.times);
return result;
}
static int maxPerfectSquares(int num1, int num2) {
int largestPerfectSqr = (int) Math.pow(Math.floor(Math.sqrt(num2)), 2);
if (largestPerfectSqr < num1) {
return 0;
}
Result result = calculatePerfectSquare(largestPerfectSqr);
int currentValue = result.base;
while (currentValue > 2) {
// check lower based values
currentValue--;
int newValue = perfectSquare(currentValue, result.times + 1);
if (newValue >= num1 && newValue < num2) {
result = calculatePerfectSquare(newValue);
currentValue = result.base;
}
}
return result.times;
}
Edit - My assumption is incorrect. Refer to the answer provided by "second".
You can remove the outer loop, num2 can be directly used to determine the number with the maximum number of recursive square roots.
requiredNumber = square(floor(sqrt(num2)));
You just need to check to see if the requiredNumber exists in the range [num1, num2] after finding it.
So the refactoring code would look something like this,
int requiredNumber = Math.pow(floor(Math.sqrt(num2)),2);
int numberOfTimes=0;
if(requiredNumber>=num1) {
if (requiredNumber == 1) {
numberOfTimes=1;
} else{
while (isCurrentNumberPerfectSquare(requiredNumber)) {
numberOfTimes++;
}
}
}
Edit 4: for a more optimal approach check my other answer.
I just leave this here if anybody wants to try to follow my thought process ;)
Edit 3:
Using prime numbers is wrong, use lowest non perfect square instead
Example [35,37]
Edit 2:
Now that I think about it there is a even better approach, especially if you assume that num1 and num2 cover a larger range.
Start with the lowest prime number 'non perfect square' and
calculate the maximum perfect square that fits into your range.
If you have found one, you are done.
If not continue with the next prime number 'non perfect square'.
As a example that works well enough for smaller ranges:
I think you can improve the outerloop. There is no need to test every number.
If you know the smallest perfect square, you can just proceed to the next perfect square in the sequence.
For example:
[16, 26]
16 -> 4 -> 2 ==> 2 perfect squares
No neeed to test 17 to 24
25 -> 5 ==> 1 perfect square
and so on ...
#Chrisvin Jem
Your assumption is not correct, see example above
Edit:
Added some code
static int countPerfectSquares(int current) {
int count = 0;
while (true) {
double squareRoot = Math.sqrt(current);
if (isCurrentNumberPerfectSquare(squareRoot)) {
count++;
current = (int) squareRoot;
} else {
return count;
}
}
}
static boolean isCurrentNumberPerfectSquare(double number) {
return ((number - Math.floor(number)) == 0);
}
static int numPerfectSquares(int num1, int num2) {
int max = 0;
if (num1 == 1) {
max = 1;
}
int sqr = Math.max(2, (int) Math.floor(Math.sqrt(num1)));
int current = (int) Math.pow(sqr, 2);
if (current < num1) {
current = (int) Math.pow(++sqr, 2);
}
while (current <= num2) {
max = Math.max(countPerfectSquares(current), max);
current = (int) Math.pow(++sqr, 2);
}
return max;
}
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
I was trying to use the code below to solve the integer reverse problem. But when I convert the int to a string and then convert the string back to int, there is an error. I am wondering if the memory allocation limiting this method.
The error is Line 4: error: incompatible types: possible lossy conversion from long to int
public class Solution {
public long reverse(int x) {
String input = String.valueOf(x);
char[] num = input.toCharArray();
StringBuffer reverse = new StringBuffer();
if(x<0){
reverse.append("-");
for(int i=num.length-1;i>0;i--){
reverse.append(num[i]);
}
}else{
for(int i=num.length-1;i>=0;i--){
reverse.append(num[i]);
}
}
return Long.parseLong(reverse.toString());
}
}
It does what you have asked for.
public static long reverseInteger(int n){
String answer = "";
if (n == Integer.MIN_VALUE)
return -8463847412L;
boolean negative = false;
if (n < 0) {
negative = true;
n = -n;
}
while (n > 0) {
answer += (n % 10);
n = n/10;
}
long toReturn = Long.parseLong(answer);
return (negative) ? -toReturn : toReturn;
}
The static keyword is optional, of course.
It depends on how you use it.
The error message you are getting is probably due to somewhere else in your code; perhaps you are assigning the value returned by reverse() (which is a long) to an int variable.
However, there is unnecessary inefficiency in your code. You are creating a String, only to re-parse it back to a number. The following code returns a reversed number without using any strings at all:
public static long reverse(int n){
long r = 0;
while (n != 0) {
r *= 10;
r += (n % 10);
n /= 10;
}
return r;
}
Note that this method works correctly for negative numbers too, without having to check for them specially.
This method works for all possible int values.
Something like this works:
public long reverse(int x) {
String input = String.valueOf(x); //123
long result = Long.parseLong(new StringBuilder(input).reverse().toString());
return result; //321
}
For my Java class, we have to write a program that displays all palindromic primes based on a number the user inputs. There are a couple other questions like this, but I need to do it without creating an array, or just typing in all of the palindromic primes.
My program works, and displays all primes, but the problem is that it displays ALL primes, not just the palindromic ones. I don't know where the error is, but I would appreciate any help I can get!
Thanks,
Ben
import java.util.Scanner;
public class PalindromePrimes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int startingPoint = 1;
int startingPrime = 2;
final int printPerLine = 10;
IsItPrime(startingPrime);
IsItPalin(startingPrime);
System.out.println("Please Enter a Number: ");
int n = in.nextInt();
while (startingPoint <= n)
{
if (IsItPrime(startingPrime) && IsItPalin(startingPrime)) {
System.out.print(startingPrime + " ");
if (startingPoint % printPerLine == 0)
System.out.println();
startingPoint++;
}
startingPrime++;
}
}
public static boolean IsItPrime(int sPrime) {
if (sPrime == 2) {
return true;
}
for(int i = 2; 2 * i < sPrime; i++) {
if(sPrime % i == 0){
return false;
}
}
return true;
}
public static boolean IsItPalin(int sPrime) {
int p;
int reverse = 0;
while (sPrime > 0) {
p = sPrime % 10;
reverse = reverse * 10 + p;
sPrime = sPrime / 10;
}
if (sPrime == reverse) {
return false;
}
return true;
}
}
You could really improve both functions:
Some notes about IsItPrime:
Check first only for even numbers (you are doing this)
The for-loop could begin in 3 and increment by 2, to check only odd numbers, the even are checked in the previous point.
The for-loop only needs to check from 3 .. sqrt(N) + 1, if the number is not prime. It would be a prime if the number is less or equal to sqrt(N) and devides N.
Function IsItPrime improve:
public static boolean IsItPrime(int sPrime) {
if (sPrime % 2 == 0 && sPrime != 2) {
return false;
}
int sqrtPrime = (int)Math.sqrt(sPrime);
for (int i = 3; i <= sqrtPrime; i += 2) {
if (sPrime % i == 0) {
return false;
}
}
return true;
}
Some notes about IsItPalin:
The return result is swapped, when sPrime == reverse is palindrome, you must return true, not false.
The other problem is that in the function you are modifying the parameter sPrime in the while-loop, you need to save the original value for comparing in sPrime == reverse.
Function IsItPalin improved:
public static boolean IsItPalin(int sPrime) {
int sPrimeBackup = sPrime;
int reverse = 0;
while (sPrime > 0) {
reverse = reverse * 10 + sPrime % 10;
sPrime = sPrime / 10;
}
return (sPrimeBackup == reverse);
}
The problem is in the IsItPalin method. You are changing the value of sPrime, but then comparing sPrime to reverse. Make a copy of sPrime and compare the copy to reverse. Also, you should return true if they are equal, not false.
It looks like the problem is with your IsItPalin method. It's almost right, except for two problems.
The first problem is this:
if (sPrime == reverse) {
return false;
}
return true;
Whenever your prime number is equal to the reverse, you're returning false! This is the opposite of what we want.
The fix is to switch "true" and "false":
if (sPrime == reverse) {
return true;
}
return false;
We can actually simplify this into a single line:
return sPrime == reverse;
The second problem is with sPrime. Within your while loop, you're decreasing sPrime, and will only exit the loop when sPrime is equal to zero. That means that the only time sPrime will be equal to reverse is when you input the value of 0. To fix this, make a copy of sPrime at the top of the method and compare the copy to reverse.
The fixed version would look like this:
public static boolean IsItPalin(int sPrime) {
int copy = sPrime;
int reverse = 0;
while (sPrime > 0) {
int p = sPrime % 10;
reverse = reverse * 10 + p;
sPrime = sPrime / 10;
}
return copy == reverse;
}
This solution doesn't involve a loop, so it's probably faster
public static boolean isPaladrome(int mNumber) {
String numToString = String.valueOf(mNumber);
int sLength = numToString.length();
int midPoint = sLength / 2;
return (new StringBuilder(numToString.substring(0, midPoint)).reverse()
.toString()).equals(numToString.substring(sLength - midPoint));
}
I have to create a class MyBigInteger to calculate the operations: mod inverse and mod power with >very big integers ( about 60 digits in Decimals or more ). To solve this, I use String to store my >numbers and create some basic functions such as add, subtract, mod, div,... But the problem I got >here is that: while my add and subtract methods work right, my multiple functions only works with >small numbers, and if I use input with numbers 7, 8 or more digits, my program will not responds. I >think my idea to use String to store big numbers may be a bad idea and If i use array to store them, >will my class work more quickly, won't it?
Below is my code.The add and subtract method seem to work correctly so I will only post the method >multiple.
First is method a MyBigInteger multiply a integer. I use it to create my multipler between two >MyBigInteger:
public class MyBigInteger {
private String val;
public static final MyBigInteger ZERO = new MyBigInteger("0");
...
private MyBigInteger mutiple( int k){
MyBigInteger result = ZERO;
if( k == 0) return result;
for( int i = 1; i <= Math.abs(k); i++) result = result.add(this);
if( k > 0) return result;
else return result.getOpposite(); // result.add(result.getOpposite()) == ZERO
}
public MyBigInteger mutiple( MyBigInteger mbi){
MyBigInteger result = ZERO;
if( mbi.toString().charAt(0) != '-'){
for( int i = mbi.toString().length() - 1; i >= 0; i--){
result = result.add(this.mutiple(Integer.parseInt(mbi.toString().charAt(mbi.toString().length() - i -1) + "")).mutiple((int)Math.pow(10, i)));
}
} else{
for( int i = mbi.toString().length() - 1 ; i >= 1; i--){
result = result.add(this.mutiple(Integer.parseInt(mbi.toString().charAt(mbi.toString().length() - i) + "")).mutiple((int)Math.pow(10, i-1)));
}
result = result.getOpposite();
}
return result;
}
Many thanks for any help you may be able to provide
Sorry for this, but the Multiplication method was fixed and It works perfectly. But that it not the only problem in my Class. I created a mod method by using a subtraction method. And In my subtraction method, I use subAbs method which is a particular subtraction for two Positive MyBigNumber.
public MyBigInteger subAbs( MyBigInteger mBI){
String result = "";
int i = this.getLength();
int j = mBI.getLength();
int s = 0;
int r = 0;
String temp = "";
String val1 = this.toString();
String val2 = mBI.toString();
if( this.equalsTo(mBI) == true ) return ZERO;
else
if( this.greaterThan(mBI) == true){
for( int k = 0; k < i - j; k++) temp += "0";
val2 = temp + val2;
for( int k = i-1; k > 0; k-- ){
//And the statement right behind this comment is the wrong line (224) in the image
s = 10 + Integer.parseInt(val1.charAt(k) + "") - Integer.parseInt(val2.charAt(k) + "") - r;
if( s >= 10){
s = s - 10;
r = 0;
} else r = 1;
result = Integer.valueOf(s).toString() + result;
}
s = Integer.parseInt(val1.charAt(0) + "") - Integer.parseInt(val2.charAt(0)+"") - r;
if( s >= 0 ) result = s + result;
else result = Integer.valueOf(s).toString() + result;
return new MyBigInteger(result);
} else return new MyBigInteger("-" + mBI.subAbs(this).toString());
}
And if I put in a big number, I get a exception:
The problem may start from the method subAbs.
Your multiply method is simply adding over and over and over. This works fine for small numbers, but when you put in large numbers you are doing tons of calculations, the computer has to take a long time to figure it out.
How would you multiply 100x12345 by hand? Would you add 12345+12345, then take that and add 12345, then take that and add 12345, and repeat 100 times? That's what your alogirthm is doing now. You should try to implement your multiply algorithm in the same way you would multiply 100x12345.
Is there any other way in Java to calculate a power of an integer?
I use Math.pow(a, b) now, but it returns a double, and that is usually a lot of work, and looks less clean when you just want to use ints (a power will then also always result in an int).
Is there something as simple as a**b like in Python?
When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent
example:
22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead
232 = 1L << 32 = (long) Math.pow(2, 32)
btw. in Kotlin you have shl instead of << so
(java) 1L << 32 = 1L shl 32 (kotlin)
Integers are only 32 bits. This means that its max value is 2^31 -1. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow uses double.
If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.
Best the algorithm is based on the recursive power definition of a^b.
long pow (long a, int b)
{
if ( b == 0) return 1;
if ( b == 1) return a;
if (isEven( b )) return pow ( a * a, b/2); //even a=(a^2)^b/2
else return a * pow ( a * a, b/2); //odd a=a*(a^2)^b/2
}
Running time of the operation is O(logb).
Reference:More information
No, there is not something as short as a**b
Here is a simple loop, if you want to avoid doubles:
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
If you want to use pow and convert the result in to integer, cast the result as follows:
int result = (int)Math.pow(a, b);
Google Guava has math utilities for integers.
IntMath
import java.util.*;
public class Power {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int num = 0;
int pow = 0;
int power = 0;
System.out.print("Enter number: ");
num = sc.nextInt();
System.out.print("Enter power: ");
pow = sc.nextInt();
System.out.print(power(num,pow));
}
public static int power(int a, int b)
{
int power = 1;
for(int c = 0; c < b; c++)
power *= a;
return power;
}
}
Guava's math libraries offer two methods that are useful when calculating exact integer powers:
pow(int b, int k) calculates b to the kth the power, and wraps on overflow
checkedPow(int b, int k) is identical except that it throws ArithmeticException on overflow
Personally checkedPow() meets most of my needs for integer exponentiation and is cleaner and safter than using the double versions and rounding, etc. In almost all the places I want a power function, overflow is an error (or impossible, but I want to be told if the impossible ever becomes possible).
If you want get a long result, you can just use the corresponding LongMath methods and pass int arguments.
Well you can simply use Math.pow(a,b) as you have used earlier and just convert its value by using (int) before it. Below could be used as an example to it.
int x = (int) Math.pow(a,b);
where a and b could be double or int values as you want.
This will simply convert its output to an integer value as you required.
A simple (no checks for overflow or for validity of arguments) implementation for the repeated-squaring algorithm for computing the power:
/** Compute a**p, assume result fits in a 32-bit signed integer */
int pow(int a, int p)
{
int res = 1;
int i1 = 31 - Integer.numberOfLeadingZeros(p); // highest bit index
for (int i = i1; i >= 0; --i) {
res *= res;
if ((p & (1<<i)) > 0)
res *= a;
}
return res;
}
The time complexity is logarithmic to exponent p (i.e. linear to the number of bits required to represent p).
I managed to modify(boundaries, even check, negative nums check) Qx__ answer. Use at your own risk. 0^-1, 0^-2 etc.. returns 0.
private static int pow(int x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
if (n < 0) { // always 1^xx = 1 && 2^-1 (=0.5 --> ~ 1 )
if (x == 1 || (x == 2 && n == -1))
return 1;
else
return 0;
}
if ((n & 1) == 0) { //is even
long num = pow(x * x, n / 2);
if (num > Integer.MAX_VALUE) //check bounds
return Integer.MAX_VALUE;
return (int) num;
} else {
long num = x * pow(x * x, n / 2);
if (num > Integer.MAX_VALUE) //check bounds
return Integer.MAX_VALUE;
return (int) num;
}
}
base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).
public int power(int base, int n){
return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));
}
There some issues with pow method:
We can replace (y & 1) == 0; with y % 2 == 0
bitwise operations always are faster.
Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.
public static long pow(long x, int y) {
long result = 1;
while (y > 0) {
if ((y & 1) == 0) {
x *= x;
y >>>= 1;
} else {
result *= x;
y--;
}
}
return result;
}
Use the below logic to calculate the n power of a.
Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n)
Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).
public int calculatePower1(int a, int b) {
if (b == 0) {
return 1;
}
int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;
int temp = 1;
for (int i = 1; i <= val; i++) {
temp *= a;
}
if (b % 2 == 0) {
return temp * temp;
} else {
return a * temp * temp;
}
}
Apache has ArithmeticUtils.pow(int k, int e).
import java.util.Scanner;
class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
try {
long x = sc.nextLong();
System.out.println(x + " can be fitted in:");
if (x >= -128 && x <= 127) {
System.out.println("* byte");
}
if (x >= -32768 && x <= 32767) {
//Complete the code
System.out.println("* short");
System.out.println("* int");
System.out.println("* long");
} else if (x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) {
System.out.println("* int");
System.out.println("* long");
} else {
System.out.println("* long");
}
} catch (Exception e) {
System.out.println(sc.next() + " can't be fitted anywhere.");
}
}
}
}
int arguments are acceptable when there is a double paramter. So Math.pow(a,b) will work for int arguments. It returns double you just need to cast to int.
int i = (int) Math.pow(3,10);
Without using pow function and +ve and -ve pow values.
public class PowFunction {
public static void main(String[] args) {
int x = 5;
int y = -3;
System.out.println( x + " raised to the power of " + y + " is " + Math.pow(x,y));
float temp =1;
if(y>0){
for(;y>0;y--){
temp = temp*x;
}
} else {
for(;y<0;y++){
temp = temp*x;
}
temp = 1/temp;
}
System.out.println("power value without using pow method. :: "+temp);
}
}
Unlike Python (where powers can be calculated by a**b) , JAVA has no such shortcut way of accomplishing the result of the power of two numbers.
Java has function named pow in the Math class, which returns a Double value
double pow(double base, double exponent)
But you can also calculate powers of integer using the same function. In the following program I did the same and finally I am converting the result into an integer (typecasting). Follow the example:
import java.util.*;
import java.lang.*; // CONTAINS THE Math library
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n= sc.nextInt(); // Accept integer n
int m = sc.nextInt(); // Accept integer m
int ans = (int) Math.pow(n,m); // Calculates n ^ m
System.out.println(ans); // prints answers
}
}
Alternatively,
The java.math.BigInteger.pow(int exponent) returns a BigInteger whose value is (this^exponent). The exponent is an integer rather than a BigInteger. Example:
import java.math.*;
public class BigIntegerDemo {
public static void main(String[] args) {
BigInteger bi1, bi2; // create 2 BigInteger objects
int exponent = 2; // create and assign value to exponent
// assign value to bi1
bi1 = new BigInteger("6");
// perform pow operation on bi1 using exponent
bi2 = bi1.pow(exponent);
String str = "Result is " + bi1 + "^" +exponent+ " = " +bi2;
// print bi2 value
System.out.println( str );
}
}