Making a basic algorithm [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
So basically I want to find a easier way to do this:
if(size == 2 || size == 6 || size == 10 || size == 14 || ...) unit /= 2;
So basically it start at 2 and then it check if equals to previous size + 4.
I need to go up to 256.
I want to know if there a easy way of doing this.
EDIT: Sorry I meant to do it all in one line, not multiple lines.

You may do this:
if ( size >= 2 && size <= 256 && size % 4 == 2 )
unit /= 2;

If it keeps getting raised by 4, you could try using module-4:
if ((size - 2) % 4 == 0 && size <= 256){
unit /= 2;
}
Or, if size can be negative but should be positive:
if ((size - 2) % 4 == 0 && size >= 0 && size <= 256){
unit /= 2;
}

You could possibly do it with a switch statement as follows:
switch(size) {
case 2:
unit /=2;
case 4:
unit /= 2;
....
}
but this is still cumbersome. Another alternative could be:
for(int i=2; i < 256; i+=4) {
if (size == i) {
unit /= 4;
}
}

I'd just use an array of possible divisors.
Extend this into a class if the number to be divided by changes.
Derive the divisor on the fly if there is a mathematical progression of some kind (such as d[n+1] = d[n] + 4).
int[] divisors = {2, 6, 10};
int doIt(int n, int unit) {
for (int i : divisors) {
if (n == i) {
unit /= 2;
}
}
return unit;
}

You can ace this in O(1) with
if ((size - 2) % 4 == 0){
/*2, 6, 10 etc*/
unit >>= (Math.min(size, 256) + 2) / 4;
}
where the bitwise shift generates the appropriate multiplication of a power of two: a touchstone for your knowledge of operator precedences.
Now the question has been updated, the operation on unit is the considerably duller unit /= 2, and you'll have to add in the newly-introduced upper-bound on size of 256.

A cryptic way of doing it:
unit >>= ((size & -253) == 2) ? 1 : 0;
Explanation:
A number in the range 2-254 is also in the range 0-255. You can do a bitwise AND with ~255 = 0xffffff00; if the value is non-zero, it is outside that range;
To check calculate number % 4, do a bitwise AND with 3; compare this to 2 to see if number % 4 == 2.
So, to check if a number meets both of these criteria, we can calculate the bitwise AND of size with the bitwise AND of the two bit masks above: if both conditions are met, the result is 2.
Hence:
(size & (~255 | 3)) == 2 (simplifies to) (size & -253) == 2.

Related

How can I count integer occurrence when the int is 0 in java? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm a beginner in java and I made a program to count the number of times an int d occurs in a given integer n i.e n = 988, d = 8 returns 2.
It works with most cases (negative, positive, etc.) but my code says n = 0, d = 1 contains 1, which is wrong. How do I add a place to my 0 without making the integer 10 (which I erroneously do in my first if statement).
public class countingints{
public static int count(int n, int d) {
n = Math.abs(n);
if(n == 0) {
n = 10;
}
int result = 0;
while (n > 0) {
int place = n % 10;
if (place == d) {
result++;
}
n /= 10;
}
return result;
}
public static void main(String[] args) {
System.out.println(count(0, 1)); //SHOULD return 0
System.out.println(count(0, 5)); //returns 0
}
}
if(n == 0) {
n = 10;
}
```
Computer just follows instructions. If n is 0, n is set to 10, and 10 contains a single 1 digit.
If perhaps your intent with this if (n == 0) n = 10 line is to ensure that e.g. count(0, 0) returns 1, then just code that in: if (n == 0 && d == 0) return 1; - that's a weird case because mathematically speaking the question 'how many times does the digit 0 show up' is tricky. You can write 15 as 0015 as well, and in many ways, 0 is just a way of writing it, the number really can be considered just a completely blank string with no digits at all.
Point is, it's logical, more or less, that your algorithm does 'weird things' when you ask it for how many zeroes are in a number, in particular when you ask it how many zeroes are in the number 0. "Weird cases" usually mean they need hardcoding, so, do that.

Making a basic algorithm - the more interesting version

See the edit history of "Making a basic algorithm". There was a palpable sense of disappointment amongst the respondents when OP changed the question, invalidating some interesting answers. So, I figure, why not ask the original question again, to allow those answers to stand.
So basically I want to find a easier way to do this:
if(size == 2) unit /= 2;
if(size == 2 || size == 6) unit /= 2;
if(size == 2 || size == 6 || size == 10) unit /= 2;
So basically it checking if size is equal to 2 and then every new line it add 4 to the last size check.
I need to go up to 256.
I want to know if there a easy way of doing this.
The fundamental criterion on the numbers checked for equality here is that the remained of size / 4 is 2. This can be detected using the modulo operator, %:
size % 4 == 2
Then there is the question of how many times to divide unit by 2. For the examples above:
For size == 2, unit /= 8 (matches all 3 conditions);
For size == 6, unit /= 4 (matches second 2 conditions);
For size == 10, unit /= 2 (matches last condition).
So the smaller the number, the more times it is divided by 8. If the maximum size checked is 10, unit is divided by 2 ^ (1 + (10 - size) / 4). This can be expressed concisely using the right-shift operator:
unit >>= 1 + (10 - size) / 4
or, more generally:
unit >>= 1 + (max_number - size) / 4
where max_number % 4 == 2.
Setting max_number = 254 (256 is specified in the question, but wouldn't feature in the expression; the last number checked would be 254), and noting that we only apply this if 2 <= size <= 254, we can express the final answer as:
if (size % 4 == 2 && size >= 2 && size <= 254) {
unit >>= 1 + (254 - size) / 4;
}
Actually, the condition can be expressed more concisely (but undoubtedly less readably) as:
if ((size & 0xffffff03) == 2)
As noted by #PaulBoddington, care needs to be taken with the size of the right shift: if unit is an int and the number of bits shifted is greater than 31, then unit should simply be set to zero.

Write a program in java to print the sum of all numbers from 50 to 250(inclusive of 50 and 250) that are multiples of 3 and not divisible by 9

/* when I run this code there is no error in fact output generated is also correct but I want to know what is the logical error in this code? please can any one explain what is the logical error. */
class abc
{
public static void main(String arg[]){
int sum=0;
//for-loop for numbers 50-250
for(int i=50;i<251;i++){
// condition to check if number should be divided by 3 and not divided by 9
if(i%3==0 & i%9!=0){
//individual number which are selected in loop
System.out.println(i);
//adding values of array so that total sum can be calculated
sum=sum+i;
}
}
//final display output for the code
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n"+sum);
}
}
My philosophy is "less code == less bugs":
int sum = IntStream.rangeClosed(50, 250)
.filter(i -> i % 3 == 0)
.filter(i -> i % 9 != 0)
.sum();
One line. Easy to read and understand. No bugs.
Change this:
if(i%3==0 & i%9!=0){
to this:
if(i%3==0 && i%9!=0){
& = bitwise and operator
&& = logical operator
Difference between & and && in Java?
The only problems I saw were:
The variable sum was undeclared
Use && in place of &
int sum = 0;
for (int i = 50; i <= 250; i++) {
if (i % 3 == 0 && i % 9 != 0) {
System.out.println(i);
sum = sum + i;
}
}
System.out.println("the sum of intergers from 50 to 250 that are multiples of 3 and not divisible by 9 \n" + sum);
Well, instead of touching every single value from 50 to 250 like you would do here for(int i=50;i<251;i++), you can consider something like this...
int i = 48;
int sum = 0;
while(i < 250) {
i += 3;
if(i%9 != 0)
sum += i;
}
This is somewhat optimized in the sense that I am skipping over values that I know are not possible candidates.
But, there is a much bigger issue in your code. The following code block prints true, sure. But, it is a bad idea to depend on the & since that is not its job. The & is for bitwise AND whereas the && is for logical AND, which is what you are trying to do.
boolean t = true;
boolean f = false;
System.out.println(f&t);
Why?
In Java, if it is a && operation, as soon as you find the first false, you are sure that the expression will evaluate to false. Meanwhile, in your implementation, it would need to evaluate both sides. f&t will evaluate to false, but the JVM would need to look at both the f and t variables. Meanwhile, on using &&, it wouldn't even need to look at the t.

determine whether an int is power of 2 [duplicate]

This question already has answers here:
How to check if a number is a power of 2
(32 answers)
Closed 7 years ago.
public class test{
public static void main(String[] args) {
int a=536870912;
System.out.print((Math.log(a)/Math.log(2)));
}
}
536870912 is a number that is power of two, but the result is 29.000000000000004, could anybody explain this? Thanks.
If n is a power of 2, then its binary representation will start with 1 and will contain only 0s after it.
So, you can do:
String binary = Integer.toBinaryString(a);
Pattern powerOfTwoPattern = Pattern.compile("10*");
System.out.println(powerOfTwoPattern.matcher(binary).matches());
Anyway, if you number is not really huge (i.e. fits the int or long range), then you can follow the suggestions here
You can use below method:-
boolean isPowerOfTwo (int x)
{
while (((x % 2) == 0) && x > 1) /* While x is even and > 1 */
x /= 2;
return (x == 1);
}
Explanation:- Repeatedly divides x by 2. It divides until either the quotient becomes 1, in which case x is a power of two, or the quotient becomes odd before reaching 1, in which case x is not a power of two.
pseudo-code following, easily adapted to java
boolean is_power_of_two(int num)
{
int i = Math.ceil(Math.log(num)/Math.log(2.0));
/*while ( i >= 0 )
{
// note 1 is taken as power of 2, i.e 2 ^ 0
// chnage i > 0 above to avoid this
if ( num == (1 << i) ) return true;
i--;
}
return false;*/
// or even this, since i is initialised in maximum power of two that num can have
return (num == (1 << i)) || (num == (1 << (i-1)));
}
NOTE it also can be done with discrete logarithm in constant-time without compiling to string represenation etc, but needs a precomputed table of discrete logarithms for base 2 or even using binary manipulation as in https://stackoverflow.com/a/600306/3591273, these approaches are constant-time but use the default representation of machine int or long

How to check if an integer can be divided by 3

How to check if my integer can be divided by 3 as below:
for(int i=0; i<24; i++){
//here, how to check if "i" can be divided by 3 completely(e.g. 3, 6, 15)?
}
Use the modulo operator.
if(i % 3 == 0)
Also see Modulo operation at Wikipedia
If you are using a loop, you can use the fact that every third number can be divided by 3.
for(int i = 0; i < 24; i += 3) {
System.out.println(i + " can be divided by 3");
System.out.println((i+1) + " cannot be divided by 3");
System.out.println((i+2) + " cannnot be divided by 3");
}
This avoids the need for a modulo and cuts the number of loops by a factor of 3.
Use the MOD operator
for(int i=0; i<24; i++){
if( i%3 == 0 )
// It is divisible by 3
}
Well, what you could do (it might be a bit faster; it is faster on my machine) is:
boolean canBeDevidedBy3 = ((int) (i * 0x55555556L >> 30) & 3) == 0;
instead of
boolean canBeDevidedBy3 = (i % 3) == 0;
However, the multiplication trick only works for -2 <= i <= 1610612735. This answer was inspired by this optimization question. But if I can give you a tip: use (i % 3) == 0. It's so much simpler, and will always work.
Check the remainder of i devided by 3
if (i % 3 == 0) {}
inside the loop:
if (i%3 == 0)
// it can be divided by 3
% is called "mod" or "modulus" and gives you the remainder when dividing two numbers.
These are all true:
6 % 3 == 0
7 % 3 == 1
7 % 4 == 3
if( i % 3 == 0 )
The % operator delivers you the rest of the division i / 3
if( i % 3 == 0 ){
System.out.println("can be divided by 3");
}else{
System.out.println("cant divide by 3");
}
Is this question for real?

Categories

Resources