Is there an elegant way in java to check if an int is equal to, or 1 larger/smaller than a value.
For example, if I check x to be around 5. I want to return true on 4, 5 and 6, because 4 and 6 are just one away from 5.
Is there a build in function to do this? Or am I better off writing it like this?
int i = 5;
int j = 5;
if(i == j || i == j-1 || i == j+1)
{
//pass
}
//or
if(i >= j-1 && i <= j+1)
{
//also works
}
Of course the above code is ugly and hard to read. So is there a better way?
Find the absolute difference between them with Math.abs
private boolean close(int i, int j, int closeness){
return Math.abs(i-j) <= closeness;
}
Based on #GregS comment about overflowing if you give Math.abs a difference that will not fit into an integer you will get an overflow value
Math.abs(Integer.MIN_VALUE - Integer.MAX_VALUE) //gives 1
By casting one of the arguments to a long Math.abs will return a long meaning that the difference will be returned correctly
Math.abs((long) Integer.MIN_VALUE - Integer.MAX_VALUE) //gives 4294967295
So with this in mind the method will now look like:
private boolean close(int i, int j, long closeness){
return Math.abs((long)i-j) <= closeness;
}
use Math.abs(x-5) <= 1 as a simple test. However, elegant is in the eye of the beholder. Strive for clarity instead.
Note than in general, for something like Glitch's fine answer or even this, there are overflow conditions that must be analyzed and understood. For correctness over all possible ints you should cast the arguments to long and perform the comparison using longs.
Related
This is the code for a function that is supposed to return true if the input is prime and returns false if it is not.
This is how I intended for it to work: lets say that y = 7, the loop starts with n=1. Since 1(n) is less that 7(y) the loop can iterate. The program checks if y divided by n has a remainder of 0, meaning that n is a factor of y. If it is true, then it checks to see if the factor does not equal 1 or y (7), because if they dont then that means that y has more factors other than its self and 1, meaning that it is not prime, so it should automatically end the function and return false. but since 7 has only two factors, 1 and 7, and they either equal 1 or itself (y) then after the end of the loop, it should return true.
I don't understand why it isn't working.
public static boolean checkIfPrime(long y) {
for ( long n =1L; n <= y; n++) {
if(y%n == 0) {
if( n != 1L || n != y) {
return false;
}
}
}
return true;
}
With a few optimizations the code will be like this
static boolean isPrime(long n){
long lim = (long) Math.sqrt(n);
if(n%2 == 0 && n != 2)
return false;
for (int i = 3; i <= lim; i=i+2)
if(n%i == 0)
return false;
return true;
}
This code:
checks if the number is even and different from 2 (all even numbers
except 2 are compound).
next iterates from 3 to sqrt(n), thats because to prove a number is
prime you don't need to check all the dividers (if you don't believe
me try, and if still don't believe use n/2 wich is enough but not the
minimum value).
For loop pace start from 3 and add 2 in each iteration getting only odd numbers as divder (we first checked that it wasn't an even number).
Remove equal to operator in n <= y. Start your loop from 2. It must be like this. ( long n =2; n < y; n++)
For what you are trying to achieve, pseudo code in my opinion should look like this:
set a flag = true;
Loop from 2 to y-1{
if(y%n==0){
flag = false
break; // Very important
}
}
check flag condition & return (if some othe computation is required) or just return flag
if( n != 1L || n != y) : is adding a check condition unnecessarily to every iteration. try to avoid it.
Why use a flag instead of direct return statement ? Just a preference, a direct return definitely would work in this case.
I am trying to better understand recursion. I am writing a basic geometric series method which I know could be done easier with a loop but that is not the purpose. The method is producing the currect output for the values of 0 and 1 which is simply 1 and 1.5. But for 2 it is outputting 1.25 when it should be 1.75. Any pointers on a better way to approach this?
public static double geometricSum(int n) {
if(n == 0){
return 1;
}
n = n * 2;
return 1.0 / n + geometricSum((int) (1/Math.pow(2, n)));
}
This happens because you are casting a float into a int.
1/(2^2)=1/4=0.25 --> 0
As you are passing your float as an int you're not getting your thing working propperly.
So 0.25 + geometricSum(0)=1.25.
On the first one happens the same. you pass the 0.5, but turned into an int so you.re not getting your aproximation propperly done.
As an advice, ALWAYS put () on your math functions in order to make the program, and you yourself, understand in which order it computes the numbers.
The first problem is the cast to int, giving the wrong result, already described by reyeselda95.
There is a second problem hidden, which is that if you fix that you get this:
public static double geometricSum(double n) {
System.err.println("Calling with " + n);
if(n == 0){
return 1;
}
n = n * 2;
return 1.0 / n + geometricSum((1/Math.pow(2, n)));
}
Calling this with the provided value of 2, leads to a loop between calls with the following values, leading to a stack overflow.
...
Calling with 0.4999999999999999
Calling with 0.5000000000000001
Calling with 0.4999999999999999
Calling with 0.5000000000000001
...
This may be the function you are looking for, if I understand correctly:
public static double geometricSum(int count) {
if (count == 0) {
return 1;
}
return geometricSum(count-1) + Math.pow(2, -count);
}
Don't cast float to int;
When using float, are you sure your formula is correct? The recursion breaks if an argument is zero, but you will get StackOverflowError when passing the result of 1.0/Math.pow(2, n) to the function.
This is my python code:
def geometricSum(k):
if k == 0:
return 1
return 1/2**k + geometricSum(k-1)
k = int(input())
print(geometricSum(k))
This is all about the power of 2 i.e. 2 Pow n where n is an integer.
Here Recursion is used to get the sequence of values for n.
In my case I've to calculate the value for 1/(2 pow n).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Ive used the following function in one of my programs.
I have tried to make sure that my code is efficient however I cannot find any help online to tell me how to recognize where I could improve...
Is there any one that can help identify if there are any parts of this where I could improve (make faster) or run more efficiently
z, s and t are all integers
powerMod(z, s, t) {
int temp = 1;
while (s > 0) {
temp = temp * z;
s = s - 1;
}
temp = temp mod t;
return temp;
}
so the overall function of this is too calculate z to the power of s then mod it by n every time. very simple yet I cannot figure out how i can make this faster as it will be used by main program 100s or 1000s of times
so something like this?
using the exponentiation by square and ive used long just in case of overflow due to int * int...
int powMod(int z, int s, int t){
long result = 1; //int * int will never exceed the size of a long
long multiplicant = z;
while(s > 0){
if(s % 2 == 1) {
result *= multiplicant;
result %= t; // do modulo on each temporary result to keep accuracy
}
multiplicant *= multiplicant;
multiplicant %= t;
s /= 2;
}
return result;
}
First, note that your code will fail to do what you description asks to do for large inputs:
...so the overall function of this is too calculate z to the power of
s then mod it by n every time. ...
However, note that your code will break for large values due to integer overflow, since you will first try to calculate a huge number, which is likely to overflow - and only then you will invoke the mode operator.
The correct way to calculate the above is using the fact that:
(x*x*x*...*x) mod t == (...(((x mod t)*x) mod t)*...*x) mod t
The second calculation will yield the correct answer for much larger inputs, only assumption needed is x*t <= Integer.MAX_VALUE, which is a much simpler assumption.
As for your request to improve performance - the power operator is efficiently calculated using exponent by squaring. Make sure you utilize the above equation in this method as well to avoid mistakes for large inputs.
Another solution is to use java's BigInteger library, specifically the method BigInteger.modPow()
Instead of building your own operator, try using Math.pow() (and add the mod part).
Why not just use Math? Seems like the fastest way to me.
powerMod(double z, double s, double t)
{
double a = Math.pow(z, s);
return Math.floorMod(a, t);
}
If you are really concerned by performance you can use Guava.IntMath.pow() which does exponentiate in O(log(n)) time. Source code of this implementation is below:
public static int pow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
return (k < Integer.SIZE) ? (1 << k) : 0;
case (-2):
if (k < Integer.SIZE) {
return ((k & 1) == 0) ? (1 << k) : -(1 << k);
} else {
return 0;
}
default:
// continue below to handle the general case
}
for (int accum = 1;; k >>= 1) {
switch (k) {
case 0:
return accum;
case 1:
return b * accum;
default:
accum *= ((k & 1) == 0) ? 1 : b;
b *= b;
}
}
}
You should also note that in most practical cases regular Math.pow() will be enough for your solution. You should think about swapping algorithms if it really slows down your program.
I have a function which checks, whether a bit in an int is set or not.
But I think there will be a much faster implementation, since this one is linear and can't be the most efficient one, although I know the int should be between 1 and 1024.
public static int getBitPos(final int n) {
if (Integer.bitCount(n) != 1)
return Constants.UNDEFINED;
else {
for (int i = 0; i < Integer.MAX_VALUE; ++i) {
if (testBit(n, i))
return i;
}
}
return Constants.UNDEFINED;
}
Where testBit is the following standard function:
public static boolean testBit(final int n, final int pos) {
int mask = 1 << pos;
return (n & mask) == mask;
}
But there mast be a faster way, isn't there? If I have the value 17 and I want to know if the 4th bit (n = 8) is set? There should be a faster way to check whether the bit for n=8 is set...
Hope you can help me...
EDIT 1:
Thanks for the support. The comments and answers brought me to my mistake. I was setting the values wrongly, which made it more complicated than needed. I was never good at bit shifting.
I set the value like this, if I wanted the second bit to be set:
value = 2;
If I wanted the 4th bit to be set too, I added the value according to the 4th bit:
value += 8;
So value was 10, and the 2nd and 4th bit were set. So I saved the numbers in my class, instead of the bit-positions (8 as value, instead of 4 for the 4th bit, ...).
After changing this, I could get rid of my unnecessary function, which was way over the top!
Thanks for all help!
Your code always returns the lowest bit that is 1, if there is only one. You can achieve the same by doing this:
int foo = whatever;
int lowestSetBit = Integer.numberOfTrailingZeros(foo) + 1;
Your code would be
public static int getBitPos(final int n) {
if (Integer.bitCount(n) == 1)
return Integer.numberOfTrailingZeros(n) + 1;
return Constants.UNDEFINED;
}
How can I do something like:
int a=5;
if(4<=a<=6){
}
in Java?
Make it two conditions:
int a=5;
if(4<=a && a<=6){
}
Apart from the obvious solution stated by others (if(4<=a && a<=6)), you can use commons-lang's IntRange:
Range range = new IntRange(4,6)
if (range.containsInteger(5)) {..}
It looks like a bit of an overkill, but depending on the situation (if it isn't as trivial) it can be very useful.
if(4 <= a && a <= 6) {
// do something
}
Of course, you could always write a function like this in some Util class:
class Util {
public static boolean inclusiveBetween(int num, int a, int b) {
return num >= a && num <= b;
}
}
and then you can do something like
if(Util.inclusiveBetween(someResourceIntensiveOpReturningInt(), 4, 6)) {
// do things
}
You can't, I don't think. What's wrong with
int a = 5;
if(a >= 4 && a <= 6) {
}
? If you need to compare many different variables, put them in an array and sort the array, then compare the arrays.
You can do this. Its ugly, but can be very slightly faster.
int a = 5;
if(a - Integer.MIN_VALUE - 4 <= 2 - Integer.MIN_VALUE) {
}
This exploits the use of underflow to turn two comparisons into one. This can save about 1-2 nano-seconds. However, in some usecases it can cost the same amount, so only try it if you are trying to micro-tune a loop.