I am working on this code challenge:
Problem Description
Given 2 integers x and n, you have to calculate x
to the power of n, modulo 10^9+7 i.e. calculate (x^n) % (10^9+7).
In other words, you have to find the value when x is raised to the
power of n, and then modulo is taken with 10^9+7.
a%b means the remainder when a divides b. For instance, 5%3 = 2, as
when we divide 5 by 3, 2 is the remainder.
Note that 10^9 is also represented as 1e9.
Input format
One line of input containing two space separated
integers, x and n.
Output format Print the required answer.
Sample Input 1 100000000 2
Sample Output 1 930000007
Explanation 1 (10^8)^2 = 10^16
10^16 % (10^9+7) = 930000007
Constraints 0 <= x < 10^9
0 <= n < 10^5
Code
The following is my code:
import java.util.*;
class ModularExponentiation {
// NOTE: Please do not modify this function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int n = sc.nextInt();
int ans = modularExponentiation(x, n);
System.out.println(ans);
}
// TODO: Implement this method
static int modularExponentiation(int x, int n) {
int M = 1000000007;
long a = (long) Math.pow(x, n);
long b = a%M;
return (int)b;
}
}
When I run my code, it succeeds for the sample test case and an edge case, but fails for 3 base cases. How do I make my code succeed all test cases?
Does this work?
public static int modularExponentiation(int x, int n) {
int modulo = 1000000007;
if (n == 0) {
return 1;
} else if (n == 1) {
return x % modulo;
} else if (n == -1) {
return 1 / x;
}
int p = modularExponentiation(x, n >> 1);
long product = ((long) p * p) % modulo;
return (int) (product * modularExponentiation(x, n & 1) % modulo);
}
Key points:
Math.pow(x,n) suffers from overflow and we can't compensate that overflow relying on result only, that is why initial idea of Math.pow(x,n) % modulo produces wrong results
We may notice that (x * x) % modulo == (x % modulo) * (x % modulo) % modulo, and it is safe to use long here as intermediate result because x % modulo < modulo and modulo * modulo < 2^63 - 1
We need to reconstruct the process, but naive approach that x^n is a product of n x's is too slow - it has O(N) time complexity, however we may notice that x^2k == (x^k)^2 and x^(2k+1) == x * (x^k)^2 - so we may use either recursion here or loop to achieve O(LogN) time complexity
alternative loop solution:
public static int modularExponentiation(int x, int n) {
int modulo = 1000000007;
long product = 1;
long p = x;
while (n != 0) {
if ((n & 1) == 1) {
product = product * p % modulo;
}
p = (p * p % modulo);
n >>= 1;
}
return (int) product;
}
If you have problem in C++ then , you can use
const unsigned int Mod=1e9+7;
I have made a function that converts a double to a simplified fraction in Java:
public static int gcm(int a, int b) {
return b == 0 ? a : gcm(b, a % b);
}
public static String toFraction(double d) {
int decimals = String.valueOf(d).split("\\.")[1].length();
int mult = (int) Math.pow(10, decimals);
int numerator = (int) (d * mult);
int denominator = mult;
// now simplify
int gcm = gcm(numerator, denominator);
numerator /= gcm;
denominator /= gcm;
return numerator + "/" + denominator;
}
It works, except for the fact that if I use toFraction(1.0/3), this will, understandably, return "715827882/2147483647". How may I fix this to return "1/3"?
You have to allow for a certain error and not all fractions can be exactly represented as scalar values.
public static String toFraction(double d, double err) {
String s = Long.toString((long) d);
d -= (long) d;
if (d > err) {
for (int den = 2, max = (int) (1 / err); den < max; den++) {
long num = Math.round(d * den);
double d2 = (double) num / den;
if (Math.abs(d - d2) <= err)
return (s.equals("0") ? "" : s + " ") + num +"/"+den;
}
}
return s;
}
public static void main(String... args) {
System.out.println(toFraction(1.0/3, 1e-6));
System.out.println(toFraction(1.23456789, 1e-6));
System.out.println(toFraction(Math.E, 1e-6));
System.out.println(toFraction(Math.PI, 1e-6));
for (double d = 10; d < 1e15; d *= 10)
System.out.println(toFraction(Math.PI, 1.0 / d));
}
prints
1/3
1 19/81
2 719/1001
3 16/113
3 1/5
3 1/7
3 9/64
3 15/106
3 16/113
3 16/113
3 3423/24175
3 4543/32085
3 4687/33102
3 14093/99532
3 37576/265381
3 192583/1360120
3 244252/1725033
3 2635103/18610450
Note: this finds the 21/7, 333/106 and 355/113 approximations for PI.
No double value is equal to one third, so the only way your program can be made to print 1/3 is if you change the specification of the method to favour "nice" answers rather than the answer that is technically correct.
One thing you could do is choose a maximum denominator for the answers, say 100, and return the closest fraction with denominator 100 or less.
Here is how you could implement this using Java 8 streams:
public static String toFraction(double val) {
int b = IntStream.rangeClosed(1, 100)
.boxed()
.min(Comparator.comparingDouble(n -> Math.abs(val * n - Math.round(val * n))))
.get();
int a = (int) Math.round(val * b);
int h = gcm(a, b);
return a/h + "/" + b/h;
}
There is no nice approach to this. double is not very good for this sort of thing. Note that BigDecimal can't represent 1/3 either, so you'll have the same problem with that class.
There are nice ways to handle this but you will need to look at special cases. For example, if the numerator is 1 then the fraction is already reduced and you simply strip out the decimal places and return what you were given.
I need to convert a float to an int, as if the comma was removed.
Example:
23.2343f -> 232343
private static int removeComma(float value)
{
for (int i = 0; ; i++) {
if((value * (float)Math.pow(10, i)) % 1.0f == 0.0f)
return (int)(value * Math.pow(10, i));
}
}
The problem is with rounding up of the number. For example if I pass 23000.2359f it becomes 23000236, because it rounded up the input to 23000.236.
Java float doesn't have that much precision, which you can see with
float f = 23000.2359f;
System.out.println(f);
which outputs
23000.236
To get the output you want, you could use a double like
double d = 23000.2359;
String v = String.valueOf(d).replace(".", "");
int val = Integer.parseInt(v);
System.out.println(val);
Output is (the requested)
230002359
you must find a way to get the number of digit after decimal place 1st. Suppose it is n. then multiply the number with 10 times n
double d= 234.12413;
String text = Double.toString(Math.abs(d));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;
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
I'm trying to write a function in Java that calculates the n-th root of a number. I'm using Newton's method for this. However, the user should be able to specify how many digits of precision they want. This is the part with which I'm having trouble, as my answer is often not entirely correct. The relevant code is here: http://pastebin.com/d3rdpLW8. How could I fix this code so that it always gives the answer to at least p digits of precision? (without doing more work than is necessary)
import java.util.Random;
public final class Compute {
private Compute() {
}
public static void main(String[] args) {
Random rand = new Random(1230);
for (int i = 0; i < 500000; i++) {
double k = rand.nextDouble()/100;
int n = (int)(rand.nextDouble() * 20) + 1;
int p = (int)(rand.nextDouble() * 10) + 1;
double math = n == 0 ? 1d : Math.pow(k, 1d / n);
double compute = Compute.root(n, k, p);
if(!String.format("%."+p+"f", math).equals(String.format("%."+p+"f", compute))) {
System.out.println(String.format("%."+p+"f", math));
System.out.println(String.format("%."+p+"f", compute));
System.out.println(math + " " + compute + " " + p);
}
}
}
/**
* Returns the n-th root of a positive double k, accurate to p decimal
* digits.
*
* #param n
* the degree of the root.
* #param k
* the number to be rooted.
* #param p
* the decimal digit precision.
* #return the n-th root of k
*/
public static double root(int n, double k, int p) {
double epsilon = pow(0.1, p+2);
double approx = estimate_root(n, k);
double approx_prev;
do {
approx_prev = approx;
// f(x) / f'(x) = (x^n - k) / (n * x^(n-1)) = (x - k/x^(n-1)) / n
approx -= (approx - k / pow(approx, n-1)) / n;
} while (abs(approx - approx_prev) > epsilon);
return approx;
}
private static double pow(double x, int y) {
if (y == 0)
return 1d;
if (y == 1)
return x;
double k = pow(x * x, y >> 1);
return (y & 1) == 0 ? k : k * x;
}
private static double abs(double x) {
return Double.longBitsToDouble((Double.doubleToLongBits(x) << 1) >>> 1);
}
private static double estimate_root(int n, double k) {
// Extract the exponent from k.
long exp = (Double.doubleToLongBits(k) & 0x7ff0000000000000L);
// Format the exponent properly.
int D = (int) ((exp >> 52) - 1023);
// Calculate and return 2^(D/n).
return Double.longBitsToDouble((D / n + 1023L) << 52);
}
}
Just iterate until the update is less than say, 0.0001, if you want a precision of 4 decimals.
That is, set your epsilon to Math.pow(10, -n) if you want n digits of precision.
Let's recall what the error analysis of Newton's method says. Basically, it gives us an error for the nth iteration as a function of the error of the n-1 th iteration.
So, how can we tell if the error is less than k? We can't, unless we know the error at e(0). And if we knew the error at e(0), we would just use that to find the correct answer.
What you can do is say "e(0) <= m". You can then find n such that e(n) <= k for your desired k. However, this requires knowing the maximal value of f'' in your radius, which is (in general) just as hard a problem as finding the x intercept.
What you're checking is if the error changes by less than k, which is a perfectly acceptable way to do it. But it's not checking if the error is less than k. As Axel and others have noted, there are many other root-approximation algorithms, some of which will yield easier error analysis, and if you really want this, you should use one of those.
You have a bug in your code. Your pow() method's last line should read
return (y & 1) == 1 ? k : k * x;
rather than
return (y & 1) == 0 ? k : k * x;