Java: round to nearest multiple of 5 (either up or down) - java

I need to round a number to nearest multiple of 5 (either up or down). For example, here are the list of numbers and the number next to it that it needs to round up/down to.
12.5 10
62.1 60
68.3 70
74.5 75
80.7 80
Numbers will only be positive.

haven't tested it, but 5*(Math.round(f/5)); should work

Nearest Multiple of 5
for Upper value
5*(Math.ceil(Math.abs(number/5)));
for Lower Value
5*(Math.floor(Math.abs(number/5)));
it gives Positive value only.

public static void main(String args[]) {
double num = 67.5;
if (num % 5 == 0)
System.out.println("OK");
else if (num % 5 < 2.5)
num = num - num % 5;
else
num = num + (5 - num % 5);
System.out.println(num);
}
Try this.

How about something like this:
return round((number/5))*5;

Gefei's solution is working, but I had to convert explicitly to double like this: 5*(Math.round((double)f/5))

There are many other solutions on this page, but I believe this is the most concise one.
To find the closest multiple of x for a given number,
let x be the multiple and num be the given number:
// The closest multiple of x <= num
int multipleOfX = x * ( num / x );
In your case:
int multipleOf5 = 5 * ( num / 5 );

In case you have an integer as input, otherwise the accepted answer will round it to down.
int value = 37;
value = (int) ( Math.round( value / 5.0 ) * 5.0 );

Related

How can I multiply all the digits in an integer (between 000 & 1000 exclusive) without using control statements or loops?

I'm trying to write a program that can multiply all the digits of a number from 0 to 1000 exclusive using only math expressions in Java. My program works fine as long as the user types in a 3-digit number, but results in 0 if they type in anything less than 100.
I have tried getting the last digit of the input with '%10' and removing the last digit with '/10' but without a control statement to detect if the input has been reduced to zero, the program ends up multiplying by 0 when a 2-digit number has been reduced to zero, giving an incorrect result.
public class MultiplyDigits {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter a number between 0 and 1000: ");
int number = input.nextInt();
int product = 1;
product*=number%10;
number/=10;
product*=number%10;
number/=10;
product*=number%10;
System.out.println(product);
}
}
An input of 55 should result in 25, but my program does 5 x 5 x 0 = 0
An input of 999 results in 729, which is correct. 9 x 9 x 9 = 729
Some more clarification, this is a problem out of the 2nd chapter of a textbook for complete novices. The author has not covered selection statements, loops, writing our own methods or classes, or anything more advanced than elementary programming, so the implication is that this is doable without those. The book has covered invoking methods in classes built into Java, although the author has only mentioned methods in the Math and System classes. For example, Math.max(), Math.min(), Math.pow(), System.currentTimeMillis();
What about this variant. To find the first number, you can decrease, first of all, the entered number by 100 and add 1 to avoid 0 during multipication. And , as recomended NVioli, the second number should be the same updated to have a possibility to enter number lower then 10. Thus, the final variant is:
int number = input.nextInt();
int t1 = 1 + (number-100) / 100;
int t2 = (1 + (number-10) / 10) % 10; \\By NVioli
int t3 = number % 10;
int product = t1 * t2 * t3;
System.out.println(product);
The first part is to extract the essential code into a separate Java method. I'm calling it dprod, which is short for "digit product".
static int dprod(int x) {
int hun = x / 100 % 10;
int ten = x / 10 % 10;
int one = x / 1 % 10;
return hun * ten * one;
}
The above code is the naive version that only works for numbers >= 100.
To treat numbers less than 100 as expected, you need to replace the hun or ten with 1 if it is 0.
static int dprod(int x) {
int hun = x < 100 ? 1 : x / 100 % 10;
int ten = x < 10 ? 1 : x / 10 % 10;
int one = x / 1 % 10;
return hun * ten * one;
}
The ?: operator is called a conditional operator, therefore it is probably not allowed under your rules. There is a possible workaround by using the ?: operator without writing it explicitly, by using the Math.max function.
static int dprod(int x) {
int hun = Math.max(100, x) / 100 % 10;
int ten = Math.max(10, x) / 10 % 10;
int one = x / 1 % 10;
return hun * ten * one;
}
The Math.max function uses the ?: operator internally, therefore it might be forbidden, too. This is subject to discussion though, since it depends on the exact wording of the rules and their intention.
If Math.max is forbidden, it is possible to implement it entirely without branches or conditions, see this C++ question, which can be translated to Java by replacing int32 with int and by replacing inline with static.
The complete code, including automatic tests, is:
package de.roland_illig.so;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class DprodTest {
static int dprod(int x) {
int hun = Math.max(x, 100) / 100 % 10;
int ten = Math.max(x, 10) / 10 % 10;
int one = x / 1 % 10;
return hun * ten * one;
}
#Test
public void testDprod() {
assertThat(dprod(999)).isEqualTo(729);
assertThat(dprod(123)).isEqualTo(6);
assertThat(dprod(99)).isEqualTo(81);
assertThat(dprod(9)).isEqualTo(9);
}
}
You could just initialize the program with a length 1000 array, initialize it with the value of each number, and then your real problem simplifies to:
System.out.println(calculatedArray[number]);
Your initialization could even take advantage of the fact that a leading 0 doesn't matter according to your rules (55 and 155 are the same result.)
calculatedArray[55] = calculcate(155);
there are some ways which can help you but all of them has a simple loop or if:
You can use digits = Logarithm of your number(10 base) and then you have number of digits, then you can use a loop to calculate the result. your loop will be repeated digit times so no matter how many digits your number has, it will always work.
You can check if your number is less than 100 and then just add 100 to that, then calculate the result, because of 1 * digit1 * digit2 there will be no error.

Can two non-nested for loops be condensed into one?

I have a sample question where we are required to find multiples of 10 between two numbers. Here's the code I've written, and although it works, is there a better way to write this code?
Scanner keyboard = new Scanner(System.in);
int value = keyboard.nextInt();
int limit = keyboard.nextInt();
int div = 10;
for (;div<value;div+=10)
System.out.print("");
for (;div<=limit;div+=10)
System.out.println(div);
keyboard.close();
The first for loop irks me. Any suggestions?
System.out.print("") does nothing, so your first loop can be re-written as:
int div = 10;
for (; div < value; div += 10)
;
The effect of that code is that div is the value of value rounded up to the nearest multiple of 10. This can be calculated as follows, using int math (where division by 10 rounds down):
int div = (value + 9) / 10 * 10;
The original code will result in a minimum value of 10, so if value <= 0 the formula will calculate incorrectly. We can use a ternary conditional operator to account for that:
int div = (value <= 10 ? 10 : (value + 9) / 10 * 10);
So, the abbreviated version of your code becomes:
Scanner keyboard = new Scanner(System.in);
int value = keyboard.nextInt();
int limit = keyboard.nextInt();
for (int div = (value <= 10 ? 10 : (value + 9) / 10 * 10); div <= limit; div += 10)
System.out.println(div);
keyboard.close();
Using java-8 :
IntStream.rangeClosed(value, limit).filter(i -> i % 10 == 0).forEach(System.out::println);
Here value is the begin index and limit is the ending index.

Java program to print exponential series for numbers 3 and 5 and limit the result to below 1000

I am new to Java programming and have tried a few problems on Project Euler. I somehow came up with my own problem of printing sequence of exponents of 3 and 5 and limit the result to below 1000. I have researched for 3 days to find the best approach to this problem but I could not find relevant articles. I have come across algorithms on exponential series but those were too advanced for my capability right now.
I would appreciate any help in solving this problem. Please see the code I have tried
public class Exponent {
public static void main (String[] args) {
// Declared integers for base and exponent
int i = 0; /* for base */
int n = 0; /* for exponent */
for (n=1; n<5; n++) {
for (i=1; i<=5; i++) {
if (i%3 == 0 || i%5 == 0) {
System.out.println(Math.pow(i,n));
}
}
}
}
}
This code prints out the following result:
3.0
5.0
9.0
25.0
27.0
125.0
81.0
625.0
My problem is that it is very apparent that I am forcing the exponent to print below 1000 by limiting the base and exponent value inside the loop
for (n=1; n<5; n++) //because n<=5 would print result for 5 power 5 which is 3125
I would like to somehow limit the result to below 1000 so not sure if this declaration is apt
int result = 1000; // result variable as 1000
Also, I want the code to print the output in alternates of 3 and 5 as shown below. My program prints the output in sequence of 3 and 5 respectively.
Desired output:
3.0
5.0
9.0
27.0
125.0
81.0
625.0
243.0
729.0
And stops there because the next value would exceed 1000.
I also wanted to know if there is any other approach instead of using Math.pow() method because it returns a double instead of an int. I would like to avoid the double value and just print as follows:
Without double:
3
5
9
27
81
125
243
625
729
Without using Math.pow() (and printing in different order ):
int[] bases = { 3, 5 };
long maxval = 1000L;
for (int base : bases) {
long value = base;
do {
System.out.println( value );
value *= base;
} while (value < maxval);
}
First create a double to store the result:
double result = 0;
Then create an infinite while loop which calculates the result using 3 and 5 and breaks out once result is above 1000.
while(true)
{
result = Math.pow(3, n);
if(result > 1000)
{
break;
}
System.out.println(((int)result));
result = Math.pow(5, n);
if(result < 1000)
{
System.out.println((int)result);
}
n++;
}
Since exponents of 3 are smaller than 5 don't break out until the maximum exponent in 3 is hit. Since the break does not occur don't print the 5 unless it is valid.
Also to print the double as an int value just cast it to an int.
EDIT:
If you are really worried about efficiency here is a faster solution:
public void calcExponents(int max)
{
int resultThree = 3;
int resultFive = 5;
while(resultThree < max)
{
System.out.println(resultThree);
if(resultFive < max)
{
System.out.println(resultFive);
}
resultThree *= 3;
resultFive *= 5;
}
}
You could also make the 3 and 5 arguments to take it one step further.
Why not check if the result is bigger than 1000, and just break out of the loop if it is?
if(Math.pow(i,n)>=1000)
break;
Hint:
3.0 = 3^1
5.0 = 5^1
9.0 = 3^2
25.0 = 5^2 // I assume you forgot it
27.0 = 3^3
125.0 = 5^3
81.0 = 3^4
625.0 = 5^4
243.0 = 3^5
729.0 = 3^6
and 3x is always smaller than 5x. So a single loop (for the x part) with two computations in the body of the loop one for 3 and one for 5 should do the job. You just have to use some condition for the less than 1000 part to avoid printing 55 and 56.
You could use a single loop, checking exponents for both 3 and 5 on each iteration, and printing each result that is less than 1000.
You just want to make sure that you break the loop once your 3's exceed 1000.
To print integer values, you can simply cast the result of Math.pow() to an int.
There are many different ways that one could write an algorithm like this. Here's a very simple (untested) example:
public class Exponent {
public static void main (String[] args) {
int i = 1; // or start at 0 if you prefer
// set the max value (could also be parsed from args)
int maxValue = 1000;
// the break condition also increments:
while (Math.pow(3, i++) < maxValue) {
int x3 = (int) Math.pow(3, i);
int x5 = (int) Math.pow(5, i);
if (x3 < maxValue) {
System.out.println(x3);
}
if (x5 < maxValue) {
System.out.println(x5);
}
}
}
}

Problems Generating A Math.random Number, Either 0 or 1

I want a random number, either 0 or 1 and then that will be returned to main() as in my code below.
import java.util.Scanner;
public class Exercise8Lab7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numFlips = 0;
int heads = 0;
int tails = 0;
String answer;
System.out.print("Please Enter The Number Of Coin Tosses You Want: ");
numFlips = input.nextInt();
for(int x = 1;x <= numFlips; x++){
if(coinToss() == 1){
answer = "Tails";
tails++;
}
else{
answer = "Heads";
heads++;
}
System.out.print("\nCoin Toss " + x + ": " + answer);
}
System.out.println("\n\n====== Overall Results ======" +
"\nPercentage Of Heads: " + (heads/numFlips)*100 + "\nPercentage Of Tails: " + (tails/numFlips)*100);
}
public static int coinToss(){
double rAsFloat = 1 * (2 + Math.random( ) );
int r = (int)rAsFloat;
return r;
}
}
Many solutions had been suggested to use the util.Random option which I have done and works perfectly but I want to sort out why I can't get this to work. Obviously I want the number to be an int myself so I convert it to an int after the random number has been generated. But no matter what I add or multiply the Math.random() by, it will always all either be Heads or all either be Tails. Never mixed.
Try this) It will generate number 0 or 1
Math.round( Math.random() ) ;
You could use boolean values of 0 or 1 based on value of Math.random() as a double between 0.0 and 1.0 and make the random generator much simpler. And you can get rid completely of the coinToss() method.
if(Math.random() < 0.5) {
answer = "Tails";
tails++;
}
Remove the coin toss method and replace the first conditional with the code above.
Math.random(); by itself will return a value between 0.0 and less than 1.0. If the value is in the lower half, [0.0, 0.5), then it has the same probability of being in the upper half, [0.5, 1.0). Therefore you can set any value in the lower half as true and upper as false.
Wierd that no one is using a modulo division for the random number.
This is the simplest implementation you can get:
Random rand = new Random();
int randomValue = rand.nextInt() % 2;
Math.round(Math.random()) will return either 0.0 and 1.0. Since both these values are well within the limits of int range they can be casted to int.
public static int coinToss(){
return (int)Math.round(Math.random());
}
(int)(Math.random()*2) also works fine in this case
its not working because of the integer math you are using, the call to 2+ Math.Random is pretty much always giving you a answer between 0.0 and 1.0.
so assuming that you recieve 0.25 as your result your maths is as follows
double d = 1* (2 + 0.25); // (result = 2
Then you are checking to see if your result == 1 ( which it never will. )
A better result would be to declare java.util.Random as a class variable and call random.nextBoolean() and simply perform your heads/tails calculation on that.
If you were to continue to use Math.random() and lets say
return Math.random() < 0.5
Your results would be ever so slightly skewed due to the fact that Math.random() cannot return 1.0, due to the fact that the java API specification states:
"Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0."
Math.random() returns a random float in the range [0.0,1.0)--that means the result can be anything from 0 up to but not including 1.0.
Your code
double rAsFloat = 1 * (2 + Math.random( ) );
will take this number in the [0.0,1.0) range; adding 2 to it gives you a number in the [2.0,3.0) range; multiplying it by 1 does nothing useful; then, when you truncate it to an integer, the result is always 2.
To get integers from this kind of random function, you need to figure out how many different integers you could return, then multiply your random number by that. If you want a "0 or 1" answer, your range is 2 different integers, so multiply Math.random() by 2:
double rAsFloat = 2 * Math.random();
This gives you a random number in the range [0.0,2.0), which can then be 0 or 1 when you truncate to an integer with (int). If, instead, you wanted something that returns 1 or 2, for example, you'd just add 1 to it:
double rAsFloat = 1 + 2 * Math.random();
I think you've already figured out that the Random class gives you what you want a lot more easily. I've decided to explain all this anyway, because someday you might work on a legacy system in some old language where you really do need to work with a [0.0,1.0) random value. (OK, maybe that's not too likely any more, but who knows.)
The problem can be translated to boolean generation as follow :
public static byte get0Or1 {
Random random = new Random();
boolean res= random.nextBoolean();
if(res)return 1;
else return 0;
}
Here it the easiest way I found without using java.util.Random.
Blockquote
Scanner input = new Scanner (System.in);
System.out.println("Please enter 0 for heads or 1 for tails");
int integer = input.nextInt();
input.close();
int random = (int) (Math.random() + 0.5);
if (random == integer) {
System.out.println("correct");
}
else {
System.out.println("incorrect");
}
System.out.println(random);
This will take a random double from (0 to .99) and add .5 to make it (.5 to 1.49). It will also cast it to an int, which will make it (0 to 1). The last line is for testing.
for(int i=0;i<100;i++){
System.out.println(((int)(i*Math.random())%2));
}
use mod it will help you!
One more variant
rand.nextInt(2);
As it described in docs it will return random int value between 0 (inclusive) and the specified value (exclusive)

How to round integer in java

I want to round the number 1732 to the nearest ten, hundred and thousand. I tried with Math round functions, but it was written only for float and double. How to do this for Integer? Is there any function in java?
What rounding mechanism do you want to use? Here's a primitive approach, for positive numbers:
int roundedNumber = (number + 500) / 1000 * 1000;
This will bring something like 1499 to 1000 and 1500 to 2000.
If you could have negative numbers:
int offset = (number >= 0) ? 500 : -500;
int roundedNumber = (number + offset) / 1000 * 1000;
(int)(Math.round( 1732 / 10.0) * 10)
Math.round(double) takes the double and then rounds up as an nearest integer. So, 1732 will become 173.2 (input parameter) on processing by Math.round(1732 / 10.0). So the method rounds it like 173.0. Then multiplying it with 10 (Math.round( 1732 / 10.0) * 10) gives the rounded down answer, which is 173.0 will then be casted to int.
Use Precision (Apache Commons Math 3.1.1)
Precision.round(double, scale); // return double
Precision.round(float, scale); // return float
Use MathUtils (Apache Commons Math) - Older versions
MathUtils.round(double, scale); // return double
MathUtils.round(float, scale); // return float
scale - The number of digits to the right of the decimal point. (+/-)
Discarded because method round(float,
scale) be used.
Math.round(MathUtils.round(1732, -1)); // nearest ten, 1730
Math.round(MathUtils.round(1732, -2)); // nearest hundred, 1700
Math.round(MathUtils.round(1732, -3)); // nearest thousand, 2000
Better solution
int i = 1732;
MathUtils.round((double) i, -1); // nearest ten, 1730.0
MathUtils.round((double) i, -2); // nearest hundred, 1700.0
MathUtils.round((double) i, -3); // nearest thousand, 2000.0
You could try:
int y = 1732;
int x = y - y % 10;
The result will be 1730.
Edit: This doesn't answer the question. It simply removes part of the number but doesn't "round to the nearest".
At nearest ten:
int i = 1986;
int result;
result = i%10 > 5 ? ((i/10)*10)+10 : (i/10)*10;
(Add zero's at will for hundred and thousand).
why not just check the unit digit...
1. if it is less than or equal to 5, add 0 at the unit position and leave the number as it is.
2. if it is more than 5, increment the tens digit, add 0 at the unit position.
ex: 1736 (since 6 >=5) the rounded number will be 1740.
now for 1432 (since 2 <5 ) the rounded number will be 1430....
I hope this will work... if not than let me know about those cases...
Happy Programming,
very simple. try this
int y = 173256457;int x = (y/10)*10;
Now in this you can replace 10 by 100,1000 and so on....
Its very easy..
int x = 1234;
int y = x - x % 10; //It will give 1230
int y = x - x % 100; //It will give 1200
int y = x - x % 1000; //It will give 1000
The above logic will just convert the last digits to 0. If you want actual round of//
For eg. 1278 this should round off to 1280 because last digit 8 > 5 for this i wrote a function check it out.
private double returnAfterRoundDigitNum(double paramNumber, int noOfDigit)
{
double tempSubtractNum = paramNumber%(10*noOfDigit);
double tempResultNum = (paramNumber - tempSubtractNum);
if(tempSubtractNum >= (5*noOfDigit))
{
tempResultNum = tempResultNum + (10*noOfDigit);
}
return tempResultNum;
}
Here pass 2 parameters one is the number and the other is position till which you have to round off.
Regards,
Abhinav
I usually do it this way:
int num = 1732;
int roundedNum = Math.round((num + 9)/10 * 10);
This will give you 1740 as the result.
Hope this will help.
int val2 = 1732;
val2 = (int)(Math.rint((double) i / 10) * 10);
The output is:1730
Have you looked at the implementation of Mathutils.round() ? It's all based on BigDecimal and string conversions. Hard to imagine many approaches that are less efficient.
Without using any math utils, rounding could be achieved to any unit as below:
double roundValue (double input, double toNearest){
//toNearest is any rounding base like 10, 100 or 1000.
double modValue = input % toNearest;
System.out.println(modValue);
if(modValue == 0d){
roundedValue = input;
}
else
{
roundedValue = ((input - modValue) + toNearest);
}
System.out.println(roundedValue);
return roundedValue;
}

Categories