Missing Return Statement - java

I am trying to write code which would, given the time of day in terms of an hour, minute, second and "day half" (i.e., AM or PM), calculate and return the fraction of the day (a value of type double) that has elapsed since midnight (12:00 AM).
For example,
System.out.print(fractionOfDay(12, 0, 0, 'A'));
would print 0.0
System.out.print(fractionOfDay(12, 0, 0, 'P'));
would print 0.5
System.out.print(fractionOfDay(11, 59, 59, 'P'));
would print 0.999988426
I have written the following code:
public class FractionOfDay {
public static double fractionOfDay(double h, double m, int s, char a ) {
if (a == 'P' && h == 12) {
double x = (h * 60 * 60) + (m * 60) + (s);
double y = x / 86400;
return y;
} else if (a == 'P' && h != 12) {
double x = ( (h + 12) * 60 * 60) + (m * 60) + (s);
double y = x / 86400;
return y;
} else if (a == 'A' && h == 12) {
double x = (m * 60) + (s);
double y = x / 86400;
} else if (a == 'A' && h != 12) {
double x = ( (h) * 60 * 60) + (m * 60) + (s);
double y = x / 86400;
return y;
}
}
public static void main(String[] args) {
System.out.println(fractionOfDay(12, 0, 0, 'P'));
}
}
However, when I try to compile this code, it gives me the error
missing return statement.
I don't understand what is wrong with the code.

That's because all of your return statements are within if statements. Java sees this and judges that there is a possibility that none of these if statements will be taken. Then what would happen? There would be no return, so it spits out an error.
So you need to add a return statement under an else clause or outside of the if/else if block entirely. Something like this will solve your problem. You would have to figure out what to do when none of your paths gets taken. In this case it will return -1 (the default value of y)
public class FractionOfDay {
public static double fractionOfDay(double h, double m, int s, char a ) {
double y = -1;
if (a == 'P' && h == 12) {
double x = (h * 60 * 60) + (m * 60) + (s);
y = x / 86400;
} else if (a == 'P' && h != 12) {
double x = ( (h + 12) * 60 * 60) + (m * 60) + (s);
y = x / 86400;
} else if (a == 'A' && h == 12) {
double x = (m * 60) + (s);
y = x / 86400;
} else if (a == 'A' && h != 12) {
double x = ( (h) * 60 * 60) + (m * 60) + (s);
y = x / 86400;
}
return y;
}
public static void main(String[] args) {
System.out.println(fractionOfDay(12, 0, 0, 'P'));
}
}

The code doesn't tell you what to do in the case where a is something other than 'A' or 'P'. Maybe you know it will never be anything else, but the compiler doesn't know that, so it believes there's a possibility that the code might hit the end of the method without returning anything, which is a no-no.
Since this is a public method, you really ought to have your code do something with cases when the arguments don't fit into one of your cases, since an outside class could screw up and call it with the wrong thing. The obvious solution is to put a throw at the end of the method, something like
throw new RuntimeException("Invalid arguments to fractionOfDay");
This will prevent the error message from occurring.

Related

Understanding the strictMath java library

I got bored and decided to dive into remaking the square root function without referencing any of the Math.java functions. I have gotten to this point:
package sqrt;
public class SquareRoot {
public static void main(String[] args) {
System.out.println(sqrtOf(8));
}
public static double sqrtOf(double n){
double x = log(n,2);
return powerOf(2, x/2);
}
public static double log(double n, double base)
{
return (Math.log(n)/Math.log(base));
}
public static double powerOf(double x, double y) {
return powerOf(e(),y * log(x, e()));
}
public static int factorial(int n){
if(n <= 1){
return 1;
}else{
return n * factorial((n-1));
}
}
public static double e(){
return 1/factorial(1);
}
public static double e(int precision){
return 1/factorial(precision);
}
}
As you may very well see, I came to the point in my powerOf() function that infinitely recalls itself. I could replace that and use Math.exp(y * log(x, e()), so I dived into the Math source code to see how it handled my problem, resulting in a goose chase.
public static double exp(double a) {
return StrictMath.exp(a); // default impl. delegates to StrictMath
}
which leads to:
public static double exp(double x)
{
if (x != x)
return x;
if (x > EXP_LIMIT_H)
return Double.POSITIVE_INFINITY;
if (x < EXP_LIMIT_L)
return 0;
// Argument reduction.
double hi;
double lo;
int k;
double t = abs(x);
if (t > 0.5 * LN2)
{
if (t < 1.5 * LN2)
{
hi = t - LN2_H;
lo = LN2_L;
k = 1;
}
else
{
k = (int) (INV_LN2 * t + 0.5);
hi = t - k * LN2_H;
lo = k * LN2_L;
}
if (x < 0)
{
hi = -hi;
lo = -lo;
k = -k;
}
x = hi - lo;
}
else if (t < 1 / TWO_28)
return 1;
else
lo = hi = k = 0;
// Now x is in primary range.
t = x * x;
double c = x - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5))));
if (k == 0)
return 1 - (x * c / (c - 2) - x);
double y = 1 - (lo - x * c / (2 - c) - hi);
return scale(y, k);
}
Values that are referenced:
LN2 = 0.6931471805599453, // Long bits 0x3fe62e42fefa39efL.
LN2_H = 0.6931471803691238, // Long bits 0x3fe62e42fee00000L.
LN2_L = 1.9082149292705877e-10, // Long bits 0x3dea39ef35793c76L.
INV_LN2 = 1.4426950408889634, // Long bits 0x3ff71547652b82feL.
INV_LN2_H = 1.4426950216293335, // Long bits 0x3ff7154760000000L.
INV_LN2_L = 1.9259629911266175e-8; // Long bits 0x3e54ae0bf85ddf44L.
P1 = 0.16666666666666602, // Long bits 0x3fc555555555553eL.
P2 = -2.7777777777015593e-3, // Long bits 0xbf66c16c16bebd93L.
P3 = 6.613756321437934e-5, // Long bits 0x3f11566aaf25de2cL.
P4 = -1.6533902205465252e-6, // Long bits 0xbebbbd41c5d26bf1L.
P5 = 4.1381367970572385e-8, // Long bits 0x3e66376972bea4d0L.
TWO_28 = 0x10000000, // Long bits 0x41b0000000000000L
Here is where I'm starting to get lost. But I can make a few assumptions that so far the answer is starting to become estimated. I then find myself here:
private static double scale(double x, int n)
{
if (Configuration.DEBUG && abs(n) >= 2048)
throw new InternalError("Assertion failure");
if (x == 0 || x == Double.NEGATIVE_INFINITY
|| ! (x < Double.POSITIVE_INFINITY) || n == 0)
return x;
long bits = Double.doubleToLongBits(x);
int exp = (int) (bits >> 52) & 0x7ff;
if (exp == 0) // Subnormal x.
{
x *= TWO_54;
exp = ((int) (Double.doubleToLongBits(x) >> 52) & 0x7ff) - 54;
}
exp += n;
if (exp > 0x7fe) // Overflow.
return Double.POSITIVE_INFINITY * x;
if (exp > 0) // Normal.
return Double.longBitsToDouble((bits & 0x800fffffffffffffL)
| ((long) exp << 52));
if (exp <= -54)
return 0 * x; // Underflow.
exp += 54; // Subnormal result.
x = Double.longBitsToDouble((bits & 0x800fffffffffffffL)
| ((long) exp << 52));
return x * (1 / TWO_54);
}
TWO_54 = 0x40000000000000L
While I am, I would say, very understanding of math and programming, I hit the point to where I find myself at a Frankenstein monster mix of the two. I noticed the intrinsic switch to bits (which I have little to no experience with), and I was hoping someone could explain to me the processes that are occurring "under the hood" so to speak. Specifically where I got lost is from "Now x is in primary range" in the exp() method on wards and what the values that are being referenced really represent. I'm was asking for someone to help me understand not only the methods themselves, but also how they arrive to the answer. Feel free to go as in depth as needed.
edit:
if someone could maybe make this tag: "strictMath" that would be great. I believe that its size and for the Math library deriving from it justifies its existence.
To the exponential function:
What happens is that
exp(x) = 2^k * exp(x-k*log(2))
is exploited for positive x. Some magic is used to get more consistent results for large x where the reduction x-k*log(2) will introduce cancellation errors.
On the reduced x a rational approximation with minimized maximal error over the interval 0.5..1.5 is used, see Pade approximations and similar. This is based on the symmetric formula
exp(x) = exp(x/2)/exp(-x/2) = (c(x²)+x)/(c(x²)-x)
(note that the c in the code is x+c(x)-2). When using Taylor series, approximations for c(x*x)=x*coth(x/2) are based on
c(u)=2 + 1/6*u - 1/360*u^2 + 1/15120*u^3 - 1/604800*u^4 + 1/23950080*u^5 - 691/653837184000*u^6
The scale(x,n) function implements the multiplication x*2^n by directly manipulating the exponent in the bit assembly of the double floating point format.
Computing square roots
To compute square roots it would be more advantageous to compute them directly. First reduce the interval of approximation arguments via
sqrt(x)=2^k*sqrt(x/4^k)
which can again be done efficiently by directly manipulating the bit format of double.
After x is reduced to the interval 0.5..2.0 one can then employ formulas of the form
u = (x-1)/(x+1)
y = (c(u*u)+u) / (c(u*u)-u)
based on
sqrt(x)=sqrt(1+u)/sqrt(1-u)
and
c(v) = 1+sqrt(1-v) = 2 - 1/2*v - 1/8*v^2 - 1/16*v^3 - 5/128*v^4 - 7/256*v^5 - 21/1024*v^6 - 33/2048*v^7 - ...
In a program without bit manipulations this could look like
double my_sqrt(double x) {
double c,u,v,y,scale=1;
int k=0;
if(x<0) return NaN;
while(x>2 ) { x/=4; scale *=2; k++; }
while(x<0.5) { x*=4; scale /=2; k--; }
// rational approximation of sqrt
u = (x-1)/(x+1);
v = u*u;
c = 2 - v/2*(1 + v/4*(1 + v/2));
y = 1 + 2*u/(c-u); // = (c+u)/(c-u);
// one Halley iteration
y = y*(1+8*x/(3*(3*y*y+x))) // = y*(y*y+3*x)/(3*y*y+x)
// reconstruct original scale
return y*scale;
}
One could replace the Halley step with two Newton steps, or
with a better uniform approximation in c one could replace the Halley step with one Newton step, or ...

increasing code performance of codility

today i heard about this website called codility where a user can give various programming test to check their code's performance.
When I started, they presented me with this sample test,
Task description A small frog wants to get to the other side of the
road. The frog is currently located at position X and wants to get to
a position greater than or equal to Y. The small frog always jumps a
fixed distance, D. Count the minimal number of jumps that the small
frog must perform to reach its target.
Write a function:
class Solution { public int solution(int X, int Y, int D); }
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example,
given:
X = 10
Y = 85
D = 30 the function should return 3,
because the frog will be positioned as follows:
after the first jump,
at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that: X, Y and D are integers within the range
[1..1,000,000,000]; X ≤ Y. Complexity: expected worst-case time
complexity is O(1); expected worst-case space complexity is O(1).
The question was pretty straight forward and it took me like 2 minutes to write the solution, which is following,
class Solution {
public int solution(int X, int Y, int D) {
int p = 0;
while (X < Y){
p++;
X = X + D;
}
return p;
}
}
However, the test result shows that the performance of my code is just 20% and I scored just 55%,
Here is the link to result, https://codility.com/demo/results/demo66WP2H-K25/
That was so simple code, where I have just used a single while loop, how could it possibly be make much faster ?
Basic math:
X + nD >= Y
nD >= Y - X
n >= (Y - X) / D
The minimum value for n will be the result of rounding up the division of (Y - X) by D.
Big O analysis for this operation:
Complexity: O(1). It's a difference, a division and a round up
Worst-case space complexity is O(1): you can have at most 3 more variables:
Difference for Y - X, let's assign this into Z.
Division between Z by D, let's assign this into E.
Rounding E up, let's assign this into R (from result).
Java(One Line), Correctness 100%, Performance 100%, Task score 100%
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int X, int Y, int D) {
return (int) Math.ceil((double) (Y - X) / (double) D);
}
}
Here is the 100% total score Python solution:
def solution(X, Y, D):
# write your code in Python 3.6
s = (Y-X)/D
return int(-(-s // 1))
class Solution {
public int solution(int x, int y, int d) {
return (y - x + d - 1) / d;
}
}
class Solution {
public int solution(int x, int y, int d) {
// write your code in Java SE 8
System.out.println("this is a debug message"+(y-x)%d);
if((y-x)%d == 0)
return ((y-x)/d);
else
return (((y-x)/d)+1);
}
}
C# got 100 out of 100 points
using System;
// you can also use other imports, for example:
// using System.Collections.Generic;
// you can write to stdout for debugging purposes, e.g.
// Console.WriteLine("this is a debug message");
class Solution {
public int solution(int X, int Y, int D) {
int Len= Y-X;
if (Len%D==0)
{
return Len/D;
}
else
{
return (Len/D)+1;
}
}
}
Here's Scala solution:
def solution(X: Int, Y: Int, D: Int): Int = {
//divide distance (Y-X) with fixed jump distance. If there is reminder then add 1 to result to
// cover that part with one jump
val jumps = (Y-X) / D + (if(((Y-X) % D) >0 ) 1 else 0)
jumps
}
Performance: https://codility.com/demo/results/trainingTQS547-ZQW/
Javascript solution, 100/100, and shorter than the existing answer:
function solution(Y, Y, D) {
return Math.ceil((Y - X) / D);
}
Here is a solution that brings the test performance to 100%
class Solution {
public int solution(int X, int Y, int D) {
if (X >= Y) return 0;
if (D == 0) return -1;
int minJump = 0;
if ((Y - X) % D == 0) {
minJump = (Y - X) / D;
} else minJump= (Y - X) / D +1;
return minJump;
}
}
JavaScript solution 100/100
function solution (x,y,d) {
if ((y-x) % d === 0) {
return (y-x)/d;
} else {
return Math.ceil((y-x)/d);
}
}
Using Java perfect code
100 score code in Java
public int solution(int X, int Y, int D) {
if(X<0 && Y<0)
return 0;
if(X==Y)
return 0;
if((Y-X)%D==0)
return (Y-X)/D;
else
return (((Y-X)/D)+1);
}
this is corrected code using java giving 91% pass
int solution(int A[]) {
int len = A.length;
if (len == 2) {
return Math.abs(A[1] - A[0]);
}
int[] sumArray = new int[A.length];
int sum = 0;
for (int j = 0; j < A.length; j++) {
sum = sum + A[j];
sumArray[j] = sum;
}
int min = Integer.MAX_VALUE;
for (int j = 0; j < sumArray.length; j++) {
int difference = Math.abs(sum - 2 * sumArray[j]);
// System.out.println(difference);
if (difference < min)
min = difference;
}
return min;
}
This is my solution with 100% (C#):
int result = 0;
if (y <= x || d == 0)
{
result = 0;
}
else
{
result = (y - x + d - 1) / d;
}
return result;
Here is my solution in PHP, 100% performance.
function solution($X, $Y, $D) {
return (int)ceil(($Y-$X)/$D); //ceils returns a float and so we cast (int)
}
Y-X gives you the actual distance object has to be travel ,if that distance is directly divsible by object jump(D) then ans will be (sum/D) if some decimal value is there then we have to add 1 more into it i.e(sum/D)+1
int sum=Y-X;
if(X!=Y && X<Y){
if(sum%D==0){
return (int )(sum/D);
}
else{
return ((int)(sum/D)+1);
}}
else{
return 0;
}
I like all the rest of the solutions, especially "(y - x + d - 1) / d". That was awesome. This is what I came up with.
public int solution(int X, int Y, int D) {
if (X == Y || X > Y || D == 0) {
return 0;
}
int total = (Y - X) / D;
int left = (Y - X) - (D * total);
if (left > 0) {
total++;
}
return total;
}
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(X, Y, D) {
let jumps = 0
//If 0 -> 100 with 2 step
// Answer would be 100/2 = 50
//If 10 -> 100 with 2 step
//Answer would be (100 - 10) / 2 = 45
jumps = Math.ceil((Y - X) / D)
return jumps
}
swift solution 100% PASS - O(1) complexity
import Foundation
import Glibc
public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
if X == Y {
return 0
}
var jumps = (Y-X)/D
if jumps * D + X < Y {
jumps += 1
}
return jumps
}
import math
def solution(X, Y, D):
if (X >= Y): return 0
if (D == 0): return -1
minJump = 0
#if ((Y - X) % D == 0):
minJump = math.ceil((Y - X) / D)
#else:
#minJump = math.ceil((Y - X) / D) +1
return minJump
This solution worked for me in Java 11:
public int solution(int X, int Y, int D) {
return X == Y ? 0 : (Y - X - 1) / D + 1;
}
Correctness 100%, Performance 100%, Task score 100%
#Test
void solution() {
assertThat(task1.solution(0, 0, 30)).isEqualTo(0);
assertThat(task1.solution(10, 10, 10)).isEqualTo(0);
assertThat(task1.solution(10, 10, 30)).isEqualTo(0);
assertThat(task1.solution(10, 30, 30)).isEqualTo(1);
assertThat(task1.solution(10, 40, 30)).isEqualTo(1);
assertThat(task1.solution(10, 45, 30)).isEqualTo(2);
assertThat(task1.solution(10, 70, 30)).isEqualTo(2);
assertThat(task1.solution(10, 75, 30)).isEqualTo(3);
assertThat(task1.solution(10, 80, 30)).isEqualTo(3);
assertThat(task1.solution(10, 85, 30)).isEqualTo(3);
assertThat(task1.solution(10, 100, 30)).isEqualTo(3);
assertThat(task1.solution(10, 101, 30)).isEqualTo(4);
assertThat(task1.solution(10, 105, 30)).isEqualTo(4);
assertThat(task1.solution(10, 110, 30)).isEqualTo(4);
}
Here is the JS implementation
function frogJumbs(x, y, d) {
if ((y - x) % d == 0) {
return Math.floor((y - x) / d);
}
return Math.floor((y - x) / d + 1);
}
console.log(frogJumbs(0, 150, 30));
100% C# solution:
public int solution(int X, int Y, int D)
{
var result = Math.Ceiling((double)(Y - X) / D);
return Convert.ToInt32(result);
}
It divides the total distance by length of a jump and rounds up the result. It came after multiple attempts and some web searches.
Here is the solution in Python giving a score of 100 on Codility:
import math
return math.ceil((Y-X)/D)

How can I round down a decimal?

I am writing a program that will simulate a cash register change calculator. It should print the change and how to give back the change ( number of twenty, tens, fives, quarters, dimes, etc).
The problem is that when I compile the program, I get a big number. I've tried rounding it down but it doesn't work. ALSO, I don't know if it is caused by the change not being rounded but I won't get the number of cents, I only get 1 $10 bill.
p.s. I am taking a high school CS course and right now I can't use other methods of rounding it, I know there is a way like the one I attempted below (casting and stuff) which I am allowed to use at the moment.
Thank you.
public class changeCash
{
public static void main(String[] args)
{
double cost = 68.90;
double amtPaid = 80.00;
double change = 0;
int twentyBill= 0;
int tenBill = 0;
int fiveBill = 0;
int oneBill = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
change = amtPaid - cost;
change = ((int)change * 10) / 10.0;
System.out.println("Your change is " +"$" + change);
double back = amtPaid - cost;
if(back >= 20)
{
twentyBill++;
back -= 20;
System.out.println(twentyBill + " $20 bill(s)");
}
else if(back >= 10)
{
tenBill++;
back -= 10;
System.out.println(tenBill + " $10 bill(s)");
}
else if(back >= 5)
{
fiveBill++;
back -= 5;
System.out.println(fiveBill + " $5 bills(s)");
}
else if(back >= 1)
{
oneBill++;
back -= 1;
System.out.println(oneBill + " $1 bills(s)");
}
else if(back >= 0.25)
{
quarters++;
back -= 0.25;
System.out.println(quarters + " qaurter(s)");
}
else if(back >= 0.10)
{
dimes++;
back -= 0.10;
System.out.println(dimes + " dime(s)");
}
else if(back >= 0.05)
{
nickels++;
back -= 0.05;
System.out.println(nickels + " nickel(s)");
}
else if(back >= 0.01)
{
pennies++;
back -= 0.01;
System.out.println(pennies + " penny(ies)");
}
}
}
Couple of issues. First, smaller one:
change = amtPaid - cost;
Change is 11.1, as it should be, but then:
change = ((int)change * 10) / 10.0;
Casts take precedence over arithmetic, so first (int)change happens (which results in 11), then it is multiplied by 10, then divided by 10.0, and you end up with 11.0 instead of 11.1.
But your bigger problem is in your if statements. You have a series of if...else. Once one of these executes, the remainder of the else blocks will not. So when you have e.g.:
if (back >= 20) {
...
} else if (back >= 10) {
...
} else if (back >= 5) {
...
} else ...
As soon as one hits, it's done. If back >= 20 is false it goes to the next. Then if back >= 10 is true, it executes that, then doesn't execute the rest, so you would want to separate them, e.g.:
if (back >= 20) {
...
}
if (back >= 10) {
...
}
if (back >= 5) {
...
}
...
That'll get you closer, but you're still not quite there. For example, what if your change is 40? That will be two 20's. But your if statement will only take away a single 20. To that end, a while loop would be appropriate. It also more accurately reflects reality. In real life if you had to give somebody $40, you wouldn't just give them a single $20 and walk away, you'd get a dirty look. You'd keep giving them $20's until the amount you owed them was less than $20. So for example:
while (back >= 20) {
...
}
while (back >= 10) {
...
}
while (back >= 5) {
...
}
...
You want your code to reflect the logic you would use in reality.
Regarding your question in comments:
... why do I get $11.099999999999994 instead of just 11.1?
Floating-point rounding error. Decimal numbers are not 100% accurate; "11.1" can't be represented precisely. You have a couple of ways to work around it. You could round to two decimals when you display the number, e.g. System.out.printf("%.2f", change). However, you may want to use int and store the number of cents, rather than using double and storing the number of dollars. Working with integers is more precise, and actually, when working with currency in important applications, integers are often used for this reason.
Simpler Solution
double d = 2.99999999;
long l = (long) d;
Math.class, floor function
double d = Math.floor(2.55555) //result: 2.0
Returns the largest (closest to positive infinity) double value that
is less than or equal to the argument and is equal to a mathematical
integer
Find below the code which works well. Tested with different values. We want to avoid more than 2 decimal places hence I have added several utility methods just to do that.
Uncomment different cost values to see its working in different scenarios.
public class ChangeCash {
public static void main(String[] args) {
double cost = 65.90;
// cost = 68.33;
// cost = 42.27;
double amtPaid = 80.00;
double change = 0;
int twentyBill = 0;
int tenBill = 0;
int fiveBill = 0;
int oneBill = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
change = amtPaid - cost;
System.out.format("Your change is $ %.2f", decimalCeil(change, true));
System.out.println();
double back = decimalCeil(change, true);
if (back >= 20) {
twentyBill++;
back -= 20;
System.out.println(twentyBill + " $20 bill(s)");
}
if (back >= 10) {
tenBill++;
back -= 10;
System.out.println(tenBill + " $10 bill(s)");
}
if (back >= 5) {
fiveBill++;
back -= 5;
System.out.println(fiveBill + " $5 bills(s)");
}
if (back >= 1) {
oneBill = (int) (back * 10) / 10;
back -= oneBill;
System.out.println(oneBill + " $1 bills(s)");
}
if (decimalCeil(back) >= 0.25) {
quarters = (int) (back * 100) / 25;
back = correct2DecimalPlaces(back, 25);
System.out.println(quarters + " qaurter(s)");
}
back = (int) (decimalCeil(back, true) * 100);
if (back >= 10) {
dimes = (int) (back / 10);
back = back % 10;
System.out.println(dimes + " dime(s)");
}
if (back >= 5) {
nickels = (int) (back / 5);
back = back % 5;
System.out.println(nickels + " nickel(s)");
}
if (back >= 1) {
pennies = (int) back;
System.out.println(pennies + " penny(s)");
}
}
private static double correct2DecimalPlaces(double back, int modulo) {
int correctTwoPlaces = (int) (back * 100) % modulo;
back = (double) correctTwoPlaces / 100;
return back;
}
private static double decimalCeil(double change) {
int temp = (int) (change * 100);
double tempWithCeil = Math.ceil(temp);
double answer = tempWithCeil / 100;
return answer;
}
private static double decimalCeil(double change, boolean decimalThreePlaces) {
double temp = change * 1000;
double tempWithCeil = Math.ceil(temp);
double answer = tempWithCeil / 1000;
return answer;
}
}

How do I do recursive multiplication when one or both of the factors is/are negative?

public static int multiply2(int num1, int num2) {
if (num1 == 0 || num2 == 0) {
return 0;
}
else {
return num1 + multiply2(num1, num2 - 1);
}
}
I just realized that it would be fun to make a program that could determine the product of two numbers, one or both being negative. I want to do it using recursive multiplication (basically repeated addition). Could some one help me out? Thanks!
if (num1 == 0 || num2 == 0) {
return 0;
}
else if( num2 < 0 ) {
return - num1 + multiply2(num1, num2 + 1);
}
else {
return num1 + multiply2(num1, num2 - 1);
}
You would test if it's negative and subtract instead of add:
public static int multiply2(int num1, int num2) {
if (num1 == 0 || num2 == 0) {
return 0;
}
else if(num2 > 0){
return num1 + multiply2(num1, num2 - 1);
}
else{
return -num1 + multiply2(num1, num2 + 1);
}
}
else if (num1 < 0 || num2 < 0) {
int signum1 = num1 < 0 ? -1 : 1;
int signum2 = num2 < 0 ? -1 : 1;
return signum1 * signum2 * multiply(signum1 * num1, signum2 * num2);
} else {
Something like that
Note: there is a signum function and Math.abs can be used for signum * num
You will need to add if number is -ve. If you see we are adding only first number and for second number condition we have to reach is 0. So if negative do+1 if positive do -1
else if (num2 < 0)
return -num1 + multiply2(num1, num2 + 1);
else
return num1 + multiply2(num1, num2 - 1);
System.out.println(multiply2(5, -6));-->-30
System.out.println(multiply2(5, 6));-->30
Instead of dealing with it multiple times in the main recursion part, a better idea would be to handle it as an edge case and just convert it into a regular case since both the assignment and return will not occur until the mathematical operation has finished.
To do this, I converted y into a positive number and then negated the result of the function as a whole once the result has returned to the negative case.
Here's my solution:
private static int product(int x, int y) {
// Negative start edge case
if (y < 0) {
return -1 * product(x, y * -1);
}
// Edge case (only for speed)
if (y == 0 || x == 0) {return 0;}
// Base case
if (y == 1) {
return x;
}
// Recursion
return x + product(x, y-1);
}
It's worth noting that even with out the 0 edge case, the method would still work. In this case the method would just need to make a few more than necessary to get the result.
Testing has concluded that this method works with either parameter being 0 and/or negative.
public static int multiply2(int num1, int num2) {
if (num1 == 0 || num2 == 0) {
return 0;
}
else {
int sign2=(int)(Math.abs(num2)/num2);
return sign2*num1 + multiply2(num1,num2-sign2);
}
}
David Wallace's answer is good but if the input is (1,124) or (-1,124) the depth of recursion (number of times the method calls itself) will be 123, not very efficient. I would suggest adding a couple of lines to test for 1 or -1. Here's a full example:
public class Multiply {
public static void main(String[] args) {
System.out.print("product = " + multiply(1, 124) );
}
public static int multiply(int x, int y) {
System.out.println("Multiply called: x = " + x + ", y = " + y);
if (x == 0 || y == 0) {
System.out.println("Zero case: x = " + x + ", y = " + y);
return 0;
}
else if (x == 1 && y > 0) {
return y;
}
else if (y == 1 && x > 0) {
return x;
}
else if ( x == -1 && y > 0) {
return -y;
}
else if ( y == -1 && x > 0) {
return -x;
}
else if( y == -1 ) {
System.out.println("y is == -1");
return -x;
}
else if( x == -1 ) {
System.out.println("x is == -1");
return -y;
}
else if( y < 0 ) {
System.out.println("y is < 0");
return -x + multiply(x, y + 1);
}
else {
System.out.println("Last case: x = " + x + ", y = " + y);
return x + multiply(x, y - 1);
}
}
}
Output:
Multiply called: x = 1, y = 124
product = 124
Okay, so I am actually working on this one for homework. Recursive solutions implement - or use - a base case against which the need to continue is determined. Now, you might say, "What on Earth does that mean?" Well, in laymen's terms, it means we can simplify our code (and, in the real world, save our software some overhead) - about which I will explain, later. Now, a part of the issue is understanding some basic math, namely, a negative plus a negative is a negative or minus a positive ( -1 + -1 = -2) depending upon the math teacher to whom you speak (we'll see that come into play in the code, below).
Now, there is some debate to be had, here. About which I will write, later.
Here is my code:
public static int multiply(int a, int b)
{
if (a == 0)
{
return result;
}
else if (a < 0) // Here, we only test to see whether the first param.
// is a negative
{
return -b + multiply(a + 1, b); // Here, remember, neg. + neg. is a neg.
} // so we force b to be negative.
else
{
result = result + b;
return multiply(Math.abs(a - 1), b);
}
}
Notice there are a two things done differently, here:
The code above does not test the second parameter to see whether the second parameter is negative (a < 0) because of the mathematical principle in the first paragraph (see bold text in first paragraph). Essentially, if I know I am multiplying (y) by a negative number (-n), I know I am taking -n and adding it together y number of times; therefore, if the multiplicand or multiplier is negative, I know I can take either of the numbers, make the number negative, and add the number to itself over and over again, e.g. -3 * 7 could be written (-3) + (-3) + (-3) + (-3)... etc. OR (-7) + (-7) + (-7)
NOW HERE IS WHAT'S UP FOR DEBATE: That above code does not test to see whether the second number (int b) is 0, i.e. multiplying by 0. Why? Well, that's personal choice (sort of). The debate here must weigh the relative significance of something: the overhead for each choice (of either running an equals-zero test or not). If we do test to see if one side is zero, each time the recursive call to multiply is made, the code must evaluate the expression; however, if we do not test for equals zero, then the code adds a bunch of zeros together n number of times. In reality, both methods "weigh" the same - so, to save memory, I leave out the code.

Rounding up a number to nearest multiple of 5

Does anyone know how to round up a number to its nearest multiple of 5? I found an algorithm to round it to the nearest multiple of 10 but I can't find this one.
This does it for ten.
double number = Math.round((len + 5)/ 10.0) * 10.0;
To round to the nearest of any value:
int round(double value, int nearest) {
return (int) Math.round(value / nearest) * nearest;
}
You can also replace Math.round() with either Math.floor() or Math.ceil() to make it always round down or always round up.
int roundUp(int n) {
return (n + 4) / 5 * 5;
}
Note - YankeeWhiskey's answer is rounding to the closest multiple, this is rounding up. Needs a modification if you need it to work for negative numbers. Note that integer division followed by integer multiplication of the same number is the way to round down.
I think I have it, thanks to Amir
double round( double num, int multipleOf) {
return Math.floor((num + multipleOf/2) / multipleOf) * multipleOf;
}
Here's the code I ran
class Round {
public static void main(String[] args){
System.out.println("3.5 round to 5: " + Round.round(3.5, 5));
System.out.println("12 round to 6: " + Round.round(12, 6));
System.out.println("11 round to 7: "+ Round.round(11, 7));
System.out.println("5 round to 2: " + Round.round(5, 2));
System.out.println("6.2 round to 2: " + Round.round(6.2, 2));
}
public static double round(double num, int multipleOf) {
return Math.floor((num + (double)multipleOf / 2) / multipleOf) * multipleOf;
}
}
And here's the output
3.5 round to 5: 5.0
12 round to 6: 12.0
11 round to 7: 14.0
5 round to 2: 6.0
6.2 round to 2: 6.0
int roundUp(int num) {
return (int) (Math.ceil(num / 5d) * 5);
}
int roundUp(int num) {
return ((num / 5) + (num % 5 > 0 ? 1 : 0)) * 5;
}
int round(int num) {
int temp = num%5;
if (temp<3)
return num-temp;
else
return num+5-temp;
}
int getNextMultiple(int num , int multipleOf) {
int nextDiff = multipleOf - (num % multipleOf);
int total = num + nextDiff;
return total;
}
int roundToNearestMultiple(int num, int multipleOf){
int floorNearest = ((int) Math.floor(num * 1.0/multipleOf)) * multipleOf;
int ceilNearest = ((int) Math.ceil(num * 1.0/multipleOf)) * multipleOf;
int floorNearestDiff = Math.abs(floorNearest - num);
int ceilNearestDiff = Math.abs(ceilNearest - num);
if(floorNearestDiff <= ceilNearestDiff) {
return floorNearest;
} else {
return ceilNearest;
}
}
This Kotlin function rounds a given value 'x' to the closest multiple of 'n'
fun roundXN(x: Long, n: Long): Long {
require(n > 0) { "n(${n}) is not greater than 0."}
return if (x >= 0)
((x + (n / 2.0)) / n).toLong() * n
else
((x - (n / 2.0)) / n).toLong() * n
}
fun main() {
println(roundXN(121,4))
}
Output: 120
Kotlin with extension function.
Possible run on play.kotlinlang.org
import kotlin.math.roundToLong
fun Float.roundTo(roundToNearest: Float): Float = (this / roundToNearest).roundToLong() * roundToNearest
fun main() {
println(1.02F.roundTo(1F)) // 1.0
println(1.9F.roundTo(1F)) // 2.0
println(1.5F.roundTo(1F)) // 2.0
println(1.02F.roundTo(0.5F)) // 1.0
println(1.19F.roundTo(0.5F)) // 1.0
println(1.6F.roundTo(0.5F)) // 1.5
println(1.02F.roundTo(0.1F)) // 1.0
println(1.19F.roundTo(0.1F)) // 1.2
println(1.51F.roundTo(0.1F)) // 1.5
}
Possible to use floor/ceil like this:
fun Float.floorTo(roundToNearest: Float): Float = floor(this / roundToNearest) * roundToNearest
Some people are saying something like
int n = [some number]
int rounded = (n + 5) / 5 * 5;
This will round, say, 5 to 10, as well as 6, 7, 8, and 9 (all to 10). You don't want 5 to round to 10 though. When dealing with just integers, you want to instead add 4 to n instead of 5. So take that code and replace the 5 with a 4:
int n = [some number]
int rounded = (n + 4) / 5 * 5;
Of course, when dealing with doubles, just put something like 4.99999, or if you want to account for all cases (if you might be dealing with even more precise doubles), add a condition statement:
int n = [some number]
int rounded = n % 5 == 0 ? n : (n + 4) / 5 * 5;
Another Method or logic to rounding up a number to nearest multiple of 5
double num = 18.0;
if (num % 5 == 0)
System.out.println("No need to roundoff");
else if (num % 5 < 2.5)
num = num - num % 5;
else
num = num + (5 - num % 5);
System.out.println("Rounding up to nearest 5------" + num);
output :
Rounding up to nearest 5------20.0
I've created a method that can convert a number to the nearest that will be passed in, maybe it will help to someone, because i saw a lot of ways here and it did not worked for me but this one did:
/**
* The method is rounding a number per the number and the nearest that will be passed in.
* If the nearest is 5 - (63->65) | 10 - (124->120).
* #param num - The number to round
* #param nearest - The nearest number to round to (If the nearest is 5 -> (0 - 2.49 will round down) || (2.5-4.99 will round up))
* #return Double - The rounded number
*/
private Double round (double num, int nearest) {
if (num % nearest >= nearest / 2) {
num = num + ((num % nearest - nearest) * -1);
} else if (num % nearest < nearest / 2) {
num = num - (num % nearest);
}
return num;
}
In case you only need to round whole numbers you can use this function:
public static long roundTo(long value, long roundTo) {
if (roundTo <= 0) {
throw new IllegalArgumentException("Parameter 'roundTo' must be larger than 0");
}
long remainder = value % roundTo;
if (Math.abs(remainder) < (roundTo / 2d)) {
return value - remainder;
} else {
if (value > 0) {
return value + (roundTo - Math.abs(remainder));
} else {
return value - (roundTo - Math.abs(remainder));
}
}
}
The advantage is that it uses integer arithmetics and works even for large long numbers where the floating point division will cause you problems.
int roundUp(int n, int multipleOf)
{
int a = (n / multipleOf) * multipleOf;
int b = a + multipleOf;
return (n - a > b - n)? b : a;
}
source: https://www.geeksforgeeks.org/round-the-given-number-to-nearest-multiple-of-10/
Praveen Kumars question elsewhere in this Thread
"Why are we adding 4 to the number?"
is very relevant. And it is why I prefer to code it like this:
int roundUpToMultipleOf5(final int n) {
return (n + 5 - 1) / 5 * 5;
}
or, passing the value as an argument:
int roundUpToMultiple(final int n, final int multipleOf) {
return (n + multipleOf - 1) / multipleOf * multipleOf;
}
By adding 1 less than the multiple you're looking for, you've added just enough to make sure that a value of n which is an exact multiple will not round up, and any value of n which is not an exact multiple will be rounded up to the next multiple.
Recursive:
public static int round(int n){
return (n%5==0) ? n : round(++n);
}
Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;
if 4.25, Output 4.25
if 4.20, Output 4.20
if 4.24, Output 4.20
if 4.26, Output 4.30
if you want to round upto 2 decimal places,then use
DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));
if up to 3 places, new DecimalFormat("#.###")
if up to n places, new DecimalFormat("#.nTimes #")
public double roundToMultipleOfFive(double x)
{
x=input.nextDouble();
String str=String.valueOf(x);
int pos=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='.')
{
pos=i;
break;
}
}
int after=Integer.parseInt(str.substring(pos+1,str.length()));
int Q=after/5;
int R =after%5;
if((Q%2)==0)
{
after=after-R;
}
else
{
after=after+(5-R);
}
return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));
}
Here's what I use for rounding to multiples of a number:
private int roundToMultipleOf(int current, int multipleOf, Direction direction){
if (current % multipleOf == 0){
return ((current / multipleOf) + (direction == Direction.UP ? 1 : -1)) * multipleOf;
}
return (direction == Direction.UP ? (int) Math.ceil((double) current / multipleOf) : (direction == Direction.DOWN ? (int) Math.floor((double) current / multipleOf) : current)) * multipleOf;
}
The variable current is the number you're rounding, multipleOf is whatever you're wanting a multiple of (i.e. round to nearest 20, nearest 10, etc), and direction is an enum I made to either round up or down.
Good luck!
Round a given number to the nearest multiple of 5.
public static int round(int n)
while (n % 5 != 0) n++;
return n;
}
You can use this method Math.round(38/5) * 5 to get multiple of 5
It can be replace with Math.ceil or Math.floor based on how you want to round off the number
Use this method to get nearest multiple of 5.
private int giveNearestMul5(int givenValue){
int roundedNum = 0;
int prevMul5, nextMul5;
prevMul5 = givenValue - givenValue%5;
nextMul5 = prevMul5 + 5;
if ((givenValue%5!=0)){
if ( (givenValue-prevMul5) < (nextMul5-givenValue) ){
roundedNum = prevMul5;
} else {
roundedNum = nextMul5;
}
} else{
roundedNum = givenValue;
}
return roundedNum;
}
if (n % 5 == 1){
n -= 1;
} else if (n % 5 == 2) {
n -= 2;
} else if (n % 5 == 3) {
n += 2;
} else if (n % 5 == 4) {
n += 1;
}
CODE:
public class MyMath
{
public static void main(String[] args) {
runTests();
}
public static double myFloor(double num, double multipleOf) {
return ( Math.floor(num / multipleOf) * multipleOf );
}
public static double myCeil (double num, double multipleOf) {
return ( Math.ceil (num / multipleOf) * multipleOf );
}
private static void runTests() {
System.out.println("myFloor (57.3, 0.1) : " + myFloor(57.3, 0.1));
System.out.println("myCeil (57.3, 0.1) : " + myCeil (57.3, 0.1));
System.out.println("");
System.out.println("myFloor (57.3, 1.0) : " + myFloor(57.3, 1.0));
System.out.println("myCeil (57.3, 1.0) : " + myCeil (57.3, 1.0));
System.out.println("");
System.out.println("myFloor (57.3, 5.0) : " + myFloor(57.3, 5.0));
System.out.println("myCeil (57.3, 5.0) : " + myCeil (57.3, 5.0));
System.out.println("");
System.out.println("myFloor (57.3, 10.0) : " + myFloor(57.3,10.0));
System.out.println("myCeil (57.3, 10.0) : " + myCeil (57.3,10.0));
}
}
OUTPUT:There is a bug in the myCeil for multiples of 0.1 too ... no idea why.
myFloor (57.3, 0.1) : 57.2
myCeil (57.3, 0.1) : 57.300000000000004
myFloor (57.3, 1.0) : 57.0
myCeil (57.3, 1.0) : 58.0
myFloor (57.3, 5.0) : 55.0
myCeil (57.3, 5.0) : 60.0
myFloor (57.3, 10.0) : 50.0
myCeil (57.3, 10.0) : 60.0

Categories