Why do we get 1 as remainder on the second println? [duplicate] - java

This question already has answers here:
How Does Modulus Divison Work
(19 answers)
Closed 5 years ago.
package PracticePackage;
public class whileLoop {
public static void main(String[] args) {
int i=1;
System.out.println("Quotient "+i/2);
System.out.println("Remainder "+i%2);
}
}

this is the fomula that Java uses to yield the remainder of its operands:
(a/b)*b+(a%b)
where a is the dividend and b is the divisor.
so in your case it's like:
int i = 1;
int b = 2;
int result = (i / b) * b + (i % b);
hence the result 1 rather than 0

1/2 = 0.5
you defined i as int
Integral division in java takes floor of the answer if the answer is a real number so 1/2 becomes 0, making 1%2 equal to 1
I hope that explains.

because integers are not real numbers so you get 1 as answer and the real part of remainder is ignored since you defined i as an integer

Related

Summing a number's digits in Java [duplicate]

This question already has answers here:
Separating the Digits in an Integer - exercise from Deitel's Java book
(11 answers)
Closed 7 years ago.
Let's say you have an integer '75'. Normally, in your head, you can add the '7' with the '5' in order to get '12'. So you split the number '75' into two different numbers 7 and 5 then add them together. That leads to my question, how can you perform that in java? Is there a Math method that does it for you?
You can use plain maths
int i = 75;
int a = i / 10; // 7
int b = i % 10; // 5
int c = a + b; // 12
You can use some code like:
int num=75;
int sum_digits=0;
while(num>0){
int digit = num%10;
num /= 10;
sum_digits += digit;
}

Java recursive method which adds up digits of an argument [duplicate]

This question already has answers here:
How to write a recursive method to return the sum of digits in an int?
(13 answers)
Closed 7 years ago.
So I have to write recursive method that adds up value of digits within a certain number. For example, digitSum (1234) returns 10 (which is the sum 1+2+3+4).
So far I have this:
public static int digitSum (int n) {
if(n<10) { return n ;} //basecase
 else return !!! ;
}
What should I add in the !!! part, thank you
Just write it in plain english: when you have 1234, initial step should be to do sum(123) + 4
When you convert it to code:
public static int digitSum (int n) {
if(n<10) {
return n
}
else
return n%10 + digitSum(n/10);
}
n%10 gives you the last digit, n/10 gets you the remaining part.
When you have n=1234, n%10 = 4 and n/10 = 123. So according to your plain english sum(123) + 4 it should be digitSum(n/10) + (n%10)
Homework?
1234 remainder 10 is 4, 1234 / 10 is 123 you schould return digitSum(123) + 4

For loop, dividing one [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
I have tried this in Javascript and have gotten my answers, but the answer I need must be more exact. I am trying to divide 1 by every number between 2 and 1000, and simply print them.
public static void main(String [] args) {
for (int i=2;i<=1000;i++){
double g = (1/i);
System.out.println(g); // print "1/1,2,3,4.....1000"
}
}
I haven't done Java in a while, so I forget my correct variable names.
Since both 1 and i are integers, integer division is being used. Either 1 or i need to be double in the 1/i section of your code so that integer division is not used. You can do something like 1.0/i or 1/((double) i) to ensure that float division is used instead.
replace 1 by 1.0D that will result into double
try this
public static void main ( String args[] ) {
for (int i=2;i<=1000;i++){
double g = (1.0/i);
System.out.println("1/"+ig);
}
output:
0.5
0.3333333333333333
0.25
0.2
0.16666666666666666
0.14285714285714285
0.125
.
.
.
.
I would do something like this (note you can have as many digits of precision as you like) utilizing BigDecimal.
public static void main(String[] args) {
java.math.BigDecimal ONE = java.math.BigDecimal.ONE;
// 50 digits of precision.
java.math.MathContext mc = new java.math.MathContext(50);
for (int i = 2; i <= 1000; i++) {
java.math.BigDecimal divisor = new java.math.BigDecimal(i);
java.math.BigDecimal result = ONE.divide(divisor, mc);
result.round(mc);
System.out.printf("%d/%d = %s\n", 1, i,
result.toString());
}
}

Can 0.999... be rounded to 1 when multiplying? [duplicate]

This question already has answers here:
Can 0.99999999999 be rounded to 1.0 when multiplying?
(2 answers)
Closed 6 years ago.
When multiplying a floating point number that is very close to 1 with an int > 0, can it ever be interpreted as 1.
That is, if Math.random() returns its highest possible result (which is 1 step below 1.0), will
(int)(Math.random() * 8)
be 8 or 7?
For a practical example, can this often-used construct give an index out of bounds error:
someArray[(int)(Math.random() * someArray.length)];
I'm specifically interested in answers for Java and ActionScript 3, but I suppose they all use the same rules for floating point arithmetic, and answers for any platform would be useful.
Update: Though I already accepted an answer, I'd still appreciate confirmation that this can't go wrong in ActionScript 3 either, since a colleague reporting that he saw it go wrong once is what partly prompted me to ask this question.
Because 8 is a power of 2, multiplying a float by it will never add or remove precision from the value unless you overflow. Multiplying by other numbers, and in particular floating point numbers (other than a negative power of 2, e.g. 0.25, 0.0625, etc.), will reduce precision.
Using Math.random in java (http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html) the value can be greater than or equal to 0.0 and less than 1.0.
Using one test with value 0.999999 the value of (int)(Math.random() * 8) is 8. You can test the experiment using the next code
public static void main(String args[]) {
for (int i = 0; i <= 100; i++) {
double frac1=0.999999999999999999 ;
double frac=Math.random() ;
int integer=(int) (frac*8);
int integer1=(int) (frac1*8);
System.out.println( integer+"-"+frac);
System.out.println( integer1+"-"+frac);
}
}
But Math.random()*8 can return other values like 1,2,3,4,5,7 or 6 depends of the value returned for Math.random. You can test this running the sample code
Actually a quick exhaustive search can show that this cannot happen for any 32bit integer with floats:
public static void main(String[] args) {
int repr = Float.floatToIntBits(1f) - 1;
float val = Float.intBitsToFloat(repr);
for (long i = 1; i <= -(long)Integer.MIN_VALUE; i++) {
if ((int) (val * i) == i) {
System.out.println("FOUND VALUE: " + i);
}
if ((int) (val * -i) == -i) {
System.out.println("FOUND VALUE: " + -i);
}
if (i % 100000000 == 0) {
System.out.println("Done: " + (double)i/Integer.MAX_VALUE);
}
}
// nothing printed
}

How to round up integer division and have int result in Java? [duplicate]

This question already has answers here:
How to round up the result of integer division?
(18 answers)
Closed 4 years ago.
I just wrote a tiny method to count the number of pages for cell phone SMS. I didn't have the option to round up using Math.ceil, and honestly it seems to be very ugly.
Here is my code:
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String message = "today we stumbled upon a huge performance leak while optimizing a raycasting algorithm. Much to our surprise, the Math.floor() method took almost half of the calculation time: 3 floor operations took the same amount of time as one trilinear interpolation. Since we could not belive that the floor-method could produce such a enourmous overhead, we wrote a small test program that reproduce";
System.out.printf("COunt is %d ",(int)messagePageCount(message));
}
public static double messagePageCount(String message){
if(message.trim().isEmpty() || message.trim().length() == 0){
return 0;
} else{
if(message.length() <= 160){
return 1;
} else {
return Math.ceil((double)message.length()/153);
}
}
}
I don't really like this piece of code and I'm looking for a more elegant way of doing this. With this, I'm expecting 3 and not 3.0000000. Any ideas?
Use Math.ceil() and cast the result to int:
This is still faster than to avoid doubles by using abs().
The result is correct when working with negatives, because -0.999 will be rounded UP to 0
Example:
(int) Math.ceil((double)divident / divisor);
To round up an integer division you can use
import static java.lang.Math.abs;
public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}
or if both numbers are positive
public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}
Another one-liner that is not too complicated:
private int countNumberOfPages(int numberOfObjects, int pageSize) {
return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}
Could use long instead of int; just change the parameter types and return type.
Google's Guava library handles this in the IntMath class:
IntMath.divide(numerator, divisor, RoundingMode.CEILING);
Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.
(message.length() + 152) / 153
This will give a "rounded up" integer.
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();
If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b
Expanding on Peter's solution, this is what I've found works for me to always round 'towards positive infinity':
public static long divideAndRoundUp(long num, long divisor) {
if (num == 0 || divisor == 0) { return 0; }
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
if (sign > 0) {
return (num + divisor - 1) / divisor;
}
else {
return (num / divisor);
}
}
this might be helpfull,,
Subtract the remainder to the legnth and make it a divisible number and then divide it with 153
int r=message.length()%153; //Calculate the remainder by %153
return (message.length()-r)/153; // find the pages by adding the remainder and
//then divide by 153

Categories