Expected this loop to be infinite but it is not - java

Here is my Java code:
public class Prog1 {
public static void main(String[] args) {
int x = 5;
while (x > 1) {
x = x + 1;
if (x < 3)
System.out.println("small x");
}
}
}
And this is the output:
small x
I was expecting an infinite loop... Any idea why it is behaving this way?

There is an infinite loop. Just in some time, x get so bit that it overflows the limit of a signed int, and it goes negative.
public class Prog1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 5;
while (x > 1) {
x = x + 1;
System.out.println(x);
if(x < 3)
System.out.println("small x");
}
}
}

x starts out 5. Then as you loop through it goes to 6, 7, 8, etc. Eventually it hits the largest possible int. The next x=x+1 sets it to the most negative int, negative 2 billion-whatever. This is less than 3 so the message is output. Then you execute the while condition again which now fails, exiting the loop.
So while it appears to be an infinite loop, it isn't really.
Is this a homework problem? Why would you have written such odd code?

Java integers are signed, and they overflow (as in C and many other languages).
Try this to check this behaviour:
public class TestInt {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
System.out.println(x);
x++;
System.out.println(x);
}
}

X is overflowing the limits of an int. Check the value by adding a println statement for x
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 5;
while (x > 1) {
x = x + 1;
if(x < 3){
System.out.println(x);
System.out.println("small x");
}
}
My jvm showed x as -2147483648

Related

Java power of number calculation problem with big numbers [duplicate]

This question already has an answer here:
Why in one case multiplying big numbers gives a wrong result?
(1 answer)
Closed 2 years ago.
I am new to Java and when I was trying to find power of number without Math.pow method I realized the answer was not right. And I want to learn why?
public class Main() {
int x = 1919;
int y = x*x*x*x;
public static void main(String[] args) {
System.out.println(y);
}
}
Output: 2043765249
But normally answer is: 13561255518721
If you go step by step, you'll see that at a moment the value becomes negative, that's because you reach Integer.MAX_VALUE which is 2^31 -1
int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
y *= x;
System.out.println(i + "> " + y);
}
0> 1919
1> 3682561
2> -1523100033
3> 2043765249
You may use a bigger type like double or BigInteger
double x = 1919;
double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13
BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721
You're using an int for the answer, you're getting a numeric overflow.
Use double or long or BigInteger for y and you'll get the right answer.
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(1919, 4));
System.out.println((double) 1919*1919*1919*1919);
}
}
Outputs the same value.
Use long instead of int
public class Main{
public static void main(String[] args) {
long x = 1919;
long y = x*x*x*x;
System.out.println(y);
}
}
Read about variables in Java.

Need a fix on my code of recursion (either get needs to return int or stackoverflow error)

public class recursionTester {
public static void main(String[] args) {
System.out.println("Your recursion is " + Recursion(5,4));
}
private static int Recursion(int recursive1, int recursive2) {
if(recursive2 == 0)
return 1;
else if (recursive2 >= 0)
return Recursion(recursive1 * Recursion(recursive1,recursive2-1), recursive2);
}
}
// I am looking more for a fix rather than a suggetion because I already know my problems
It looks like you want to calculate the value of x raised to the power of y (i.e. x ^ y) using recursion. The important thing you need to keep in mind is, you need to terminate the function call with some condition; otherwise, it will become endless.
public class RecursionTester {
public static void main(String[] args) {
System.out.println("5 ^ 4 = " + power(5, 4));
}
private static int power(int x, int y) {
if (y == 0) // Because x ^ 0 = 1
return 1;
return x * power(x, y - 1);
}
}
Output:
5 ^ 4 = 625
Is this what you were looking for? Feel free to comment if it isn't the case.

How to recursively calculate a number raised to a power?

I have tried:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
This does not yield a value as I'm not sure how to do that.
public int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
static int power(int x, int y)
{
// Initialize result
int temp;
if( y == 0) // Base condition
return 1;
temp = power(x, y/2); // recursive calling
if (y%2 == 0) //checking whether y is even or not
return temp*temp;
else
return x*temp*temp;
}
Well others have written solution which gives you correct answer but their time complexity is O(n) as you are decreasing the power only by 1. Below solution will take less time O(log n). The trick here is that
x^y = x^(y/2) * x^(y/2)
so we only need to calculate x^(y/2) and then square it. Now if y is even then there is not problem but when y is odd we have to multiply it with x. For example
3^5 = 3^(5/2) * 3^(5/2)
but (5/2) = 2 so above equation will become 3^2 * 3^2, so we have to multiply it with 3 again then it will become 3 * 3^(5/2) * 3^(5/2)
then 3^2 will be calculated as 3^(2/1) * (3^2/1) here it no need to multiply it with 3.
public static double pow(int a, int pow) {
if (pow == 0)
return 1;
if (pow == 1)
return a;
if (pow == -1)
return 1. / a;
if (pow > 1)
return a * pow(a, pow - 1);
return 1. / (a * pow(a, -1 * (pow + 1)));
}
Considering X as number and n as power and if both are positive integers
public static int power(int n, int X) {
if (n == 0) {
return 1;
} else if(n == 1) {
return X;
} else {
return X * power(n-1, X);
}
}
Let's re-write your function:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
First of all, lets change void to int.
Afterthat, when n equals to 1, we return the result as X, because X^1 = X:
static public int power(int n, int X) {
if (n>1) {
return X * power(n-1, X);
}
return X;
}
Scanner s = new Scanner(System.in) ;
System.out.println("Enter n");
int n = s.nextInt();
System.out.println("Enter x");
int x =s.nextInt();
if (n>0){
double pow =Math.pow(n,x);
System.out.println(pow);
}
While others have given you solutions in terms of code, I would like to focus on why your code didn't work.
Recursion is a programming technique in which a method (function) calls itself. All recursions possess two certain characteristics:
When it calls itself, it does so to solve a smaller problem. In your example, to raise X to the power N, the method recursively calls itself with the arguments X and N-1, i.e. solves a smaller problem on each further step.
There's eventually a version of the problem which is trivial, such that the recursion can solve it without calling itself and return. This is called base case.
If you are familiar with mathematical induction, recursion is its programming equivalent.
Number two above is what your code is lacking. Your method never returns any number. In the case of raising a number to a power, the base case would be to solve the problem for the number 0 as raising zero to any power yields one, so the code does not need to call itself again to solve this.
So, as others have already suggested, you need two corrections to your code:
Add a return type for the method.
State the base case explicitly.
public class HelloWorld{
public long powerfun(int n,int power,long value){
if(power<1){
return value;
}
else{
value = value * n;
return powerfun(n,power-1,value);
}
}
public static void main(String []args){
HelloWorld hello = new HelloWorld();
System.out.println(hello.powerfun(5,4,1));
}
}
I've tried to add comments to explain the logic to you.
//Creating a new class
public class RecursivePower {
// Create the function that will calculate the power
// n is the number to be raised to a power
// x is the number by which we are raising n
// i.e. n^x
public static int power(int n, int x){
// Anything raised to the 0th power is 1
// So, check for that
if (x != 0){
// Recursively call the power function
return (n * power(n, x-1));
// If that is true...
}else{
return 1;
} //end if else
} //end power
// Example driver function to show your program is working
public static void main(String[] args){
System.out.println("The number 5 raised to 6 is " + power(5,6));
System.out.println("The number 10 raised to 3 is " + power(10,3));
} //end psvm
} //end RecursivePower

greater than or equal java for loop nested

If I only put y>x; y--; in the inner loop it prints 5432 but when I put y>=x; y--; in the inner loop it prints 54321. What happened there?
What does y>=x; y--; mean? It means y is greater than or equal to x right? But why did it print 54321?
public class TestClass {
public static void main (String[] args) {
int x;
int y;
for(x=1; x<=5; x++){
for(y=5; y>=x; y--){
System.out.print(y);
}
System.out.println();
}
}
}
if y > x and x is 1 then 1 will not be included in you printed list as y will never be less then x which is 1. When you made it = x then you allowed 1 to be allowed by y

Simple syntax error in my while loop

Hi doing some revising for an exam and came upon this past question.
Write a while loop to print the odd numbers between 0 and 10.
I've been toying about and trying to Google but its such a simple thing and its confusing me. I know its a simple syntax error somewhere.
I have tried moving the x++ about, tried moving the print statement about, just not getting it. can somebody shine light on this please. I would normally use a for loop as it would be easier but the question asks for a while loop.
public class OddNumbersWhile {
public static void main (String[]args){
int x = 0;
while (x <10){
if (x % 2 !=0) {
x++;
System.out.println(x);
}} }}
You should put your closing braces on separate lines.
And here's the problem: You're incrementing x in your if-statement thus resulting in an infinite loop once the if-statement fails to trigger since your while condition cannot be reached.
This is probably closer to what you're after.
public class OddNumbersWhile {
public static void main (String[]args){
int x = 0;
while (x <10){
if (x % 2 !=0) {
System.out.println(x);
}
x++;
}
}
}
try this
public class OddNumbersWhile {
public static void main (String[]args){
int x = 0;
while (x < 10){
if (x % 2 != 0) {
System.out.println(x);
}
x++;
}
}
}
you define x = 0, when the while loop begins, you say:
if (x % 2 !=0)
but x % 2 is = 0, because x is 0, so x++ will never run.
P.S.
Ok, N0ir gave you the code. I was trying to bring you to the solution using logic.
You should move x++ outside of the if statement.
public class OddNumbersWhile {
public static void main (String[]args){
int x = 0;
while (x <10){
if (x % 2 !=0) {
System.out.println(x);
}
x++;
}
}
}

Categories