For some reason when dealing with large numbers, the modulus operator doesnt give me the correct output, have a look at the code
double x = Math.pow(65,17) % 3233;
The output is supposed to be 2790
But the output is 887.0
I am sure its something silly but i cant get around it. Thanks in advance
The result of Math.pow(65, 17) cannot be represented exactly as a double, and is getting rounded to the nearest number that can.
The pow(a, b) % c operation is called "modular exponentiation". The Wikipedia page contains lots of ideas for how you might go about computing it.
Here is one possibility:
public static int powmod(int base, int exponent, int modulus) {
if (exponent < 0)
throw new IllegalArgumentException("exponent < 0");
int result = 1;
while (exponent > 0) {
if ((exponent & 1) != 0) {
result = (result * base) % modulus;
}
exponent >>>= 1;
base = (base * base) % modulus;
}
return result;
}
You can use int like this
int n = 65;
for (int i = 1; i < 17; i++)
n = n * 65 % 3233;
System.out.println(n);
or BigInteger like
System.out.println(BigInteger.valueOf(65).pow(17).mod(BigInteger.valueOf(3233)));
both print
2790
Related
I am trying to use Modulo 10^9+7 (or 1000000007) with a very large long number but I am not getting the correct result.
long M = 1000000007;
int num = 212;
int val = 9;
long sol = (long)Math.pow(val,num) % M ;
I should get the output as
541416750(mod10^9+7)
but what I am getting is
291172003
912 overflows long.
Also double Math.pow loses precision, so corrupts the modulo value.
(If an 8 byte long overflows, an 8 byte double can merely approximate the value, especially losing least significant digits.)
One could use BigInteger for a straight-forward solution.
You might also exploit a * b % n == ((a % n) * (b % n)) % n to reduce the power:
long modPow(int var, int num) {
long m = 1;
while (num > 0) {
m = (m * var) % M;
--num;
}
return m;
}
This is not the best solution, but the question reeks of math & programming class,
because of the modulo knowledge.
As M is an int, the return value could be an int, casted.
I am trying to write a recursive implementation of a method that takes a non-negative argument, and returns the sum of the squares of its digits. For example, sumSquareDigits(10) should return 1 and sumSquareDigits(103) should return 10.
This is my code :
public static int sumSquareDigits(int n) {
if (n < 10) return n^2;
return (((n % 10)^2) + sumSquareDigits(n/10));
}
For example for an given integer 625, it would be something like:
(625 % 10)^2 + (62,5 % 10)^2 + (6,25)^2 = 5^2 + 2^2 + (6,25)^2
which of course is wrong because the last term should be 6 and not 6,25. What I am looking for is a way to truncate 6,25 so that it becomes 6.
How do we do this? And I'd appreciate any hints to implement this function better (I'm new in Java).
Thanks!
In Java, ^ is not "to the power" of, it is the bitwise XOR operator. To perform powers in Java use Math.pow. Bear in mind that Math.pow returns a double so you will need to cast it to an int if you only want a whole number. E.g.
if (n < 10) return (int)Math.pow(n, 2);
Of course, as msandiford pointed out, if you only need to calculate powers of 2, it is probably easier to just multiply a number by itself. E.g.
if (n < 10) return n * n;
The ^ is for the bitwise XOR operator. You could use Math.pow, and cast the results to int since Math.pow returns a double:
public static int sumSquareDigits(int n) {
if (n < 10) return (int) Math.pow(n, 2);
return (int)((Math.pow((n % 10), 2)) + sumSquareDigits(n/10));
}
Or since it's only squared, just multiply the base by itself:
public static int sumSquareDigits(int n) {
if (n < 10) return n * n;
return ((n % 10) * (n % 10)) + sumSquareDigits(n/10);
}
I have to make a multiplication function without the * or / operators. I have already made a method like this.
for(int i=0; i < number1; i++){
result += number2;
}
System.Out.println(result);
Now, here is my problem: It was fine until my lecturer change the topic, where the multiplication method must be can multiply decimal value. I had no idea how I can make multiplication method which can work on decimal value with just + and - operator.
yeah you can use log for the multiplication.
log(a*b)=log(a)+log(b)
and then find out the exponential value of log(a)+log(b)
and then you can convert the sign..
for example:
-9*8=-72
log(9*8)=log(9)+log(8)=2.19+2.07=4.27
e^4.27=72
now there is only one -ve no. then it is -72
else it's 72
I'm writing the function for:
void multiply(int num1,int num2)
{
int counter=0;
if(num1<0)
{counter++;num1+=num1+num1;}
if(num2<0)
{counter++;num2+=num2+num2;}
double res=Math.log(num1)+Math.log(num2);
int result=(int)Math.exp(res);
if(counter%2==0)
System.out.println("the result is:"+result);
else
System.out.println("the result is:-"+result);
}
hope this will help you....
You take the decimal numbers and move the decimal point step by step until there is an int left: 0.041 -> 1. step 0.41 -> 2. step 4.1 -> 3. step 41
multiplying 0.041 * 3 could be done by doing the above step 3 times, multiplying 41 * 3 = 123. For the result you take the 123 and undu the steps: 1. 12.3, 2. 1.23, 3. 0.123. There is your result: 0.123 = 0.041 * 3.
Edit:
To determine the number of decimals for each number, you might find the answer in this question: How many decimal Places in A Double (Java)
Answers show within others two ways to solve this quite easy: putting the number to a String and checking where in this String the "."-DecimalPoint occurs, or using the BigDecimal type which has a scale()-Method returning the number of decimals.
You shouldn't expect whole perfect code: But here is a hint to achieve this.
Try to use recursion technique instead for loops.
public double multiplyMe(double x, double y)
{
if(y == 0 || x == 0)
return 0;
if(y > 0 && x > 0 )
return (x + multiplyMe(x, y-1)); // multiply positive
if(y < 0 || x < 0 )
return - multiplyMe(x, -y); // multiply negative
}
one more way by using log:
10 raise to power ( sum of log10(x) and log10(y) )
This approach might be easier to understand. You have to add a b times, or equivalently, b a times. In addition, you need to handle 4 different cases where a and b can be either positive or negative.
public int multiply(int a, int b){
int result = 0;
if (a < 0 && b < 0){
for (int i = a; i <= -1; i++)
result-=b;
}
else if (a < 0){
for (int i = 1; i <= b; i++)
result+=a;
}
else if (b < 0){
for (int i = 1; i <= a; i++)
result+=b;
}
else {
for (int i = 1; i <= b; i++)
result+=a;
}
return result;
}
public static void main(String[] args){
System.out.println(multiply(3,-13)); // -39
}
(note: not the same as this other question since the OP never explicitly specified rounding towards 0 or -Infinity)
JLS 15.17.2 says that integer division rounds towards zero. If I want floor()-like behavior for positive divisors (I don't care about the behavior for negative divisors), what's the simplest way to achieve this that is numerically correct for all inputs?
int ifloor(int n, int d)
{
/* returns q such that n = d*q + r where 0 <= r < d
* for all integer n, d where d > 0
*
* d = 0 should have the same behavior as `n/d`
*
* nice-to-have behaviors for d < 0:
* option (a). same as above:
* returns q such that n = d*q + r where 0 <= r < -d
* option (b). rounds towards +infinity:
* returns q such that n = d*q + r where d < r <= 0
*/
}
long lfloor(long n, long d)
{
/* same behavior as ifloor, except for long integers */
}
(update: I want to have a solution both for int and long arithmetic.)
If you can use third-party libraries, Guava has this: IntMath.divide(int, int, RoundingMode.FLOOR) and LongMath.divide(int, int, RoundingMode.FLOOR). (Disclosure: I contribute to Guava.)
If you don't want to use a third-party library for this, you can still look at the implementation.
(I'm doing everything for longs since the answer for ints is the same, just substitute int for every long and Integer for every Long.)
You could just Math.floor a double division result, otherwise...
Original answer:
return n/d - ( ( n % d != 0 ) && ( (n<0) ^ (d<0) ) ? 1 : 0 );
Optimized answer:
public static long lfloordiv( long n, long d ) {
long q = n/d;
if( q*d == n ) return q;
return q - ((n^d) >>> (Long.SIZE-1));
}
(For completeness, using a BigDecimal with a ROUND_FLOOR rounding mode is also an option.)
New edit: Now I'm just trying to see how far it can be optimized for fun. Using Mark's answer the best I have so far is:
public static long lfloordiv2( long n, long d ){
if( d >= 0 ){
n = -n;
d = -d;
}
long tweak = (n >>> (Long.SIZE-1) ) - 1;
return (n + tweak) / d + tweak;
}
(Uses cheaper operations than the above, but slightly longer bytecode (29 vs. 26)).
There's a rather neat formula for this that works when n < 0 and d > 0: take the bitwise complement of n, do the division, and then take the bitwise complement of the result.
int ifloordiv(int n, int d)
{
if (n >= 0)
return n / d;
else
return ~(~n / d);
}
For the remainder, a similar construction works (compatible with ifloordiv in the sense that the usual invariant ifloordiv(n, d) * d + ifloormod(n, d) == n is satisfied) giving a result that's always in the range [0, d).
int ifloormod(int n, int d)
{
if (n >= 0)
return n % d;
else
return d + ~(~n % d);
}
For negative divisors, the formulas aren't quite so neat. Here are expanded versions of ifloordiv and ifloormod that follow your 'nice-to-have' behavior option (b) for negative divisors.
int ifloordiv(int n, int d)
{
if (d >= 0)
return n >= 0 ? n / d : ~(~n / d);
else
return n <= 0 ? n / d : (n - 1) / d - 1;
}
int ifloormod(int n, int d)
{
if (d >= 0)
return n >= 0 ? n % d : d + ~(~n % d);
else
return n <= 0 ? n % d : d + 1 + (n - 1) % d;
}
For d < 0, there's an unavoidable problem case when d == -1 and n is Integer.MIN_VALUE, since then the mathematical result overflows the type. In that case, the formula above returns the wrapped result, just as the usual Java division does. As far as I'm aware, this is the only corner case where we silently get 'wrong' results.
return BigDecimal.valueOf(n).divide(BigDecimal.valueOf(d), RoundingMode.FLOOR).longValue();
I need a function in Java to give me number of bytes needed to represent a given integer. When I pass 2 it should return 1, 400 -> 2, 822222 -> 3, etc.
#Edit: For now I'm stuck with this:
numOfBytes = Integer.highestOneBit(integer) / 8
Don't know exactly what highestOneBit() does, but have also tried this:
numOfBytes = (int) (Math.floor(Math.log(integer)) + 1);
Which I found on some website.
static int byteSize(long x) {
if (x < 0) throw new IllegalArgumentException();
int s = 1;
while (s < 8 && x >= (1L << (s * 8))) s++;
return s;
}
Integer.highestOneBit(arg) returns only the highest set bit, in the original place. For example, Integer.highestOneBit(12) is 8, not 3. So you probably want to use Integer.numberOfTrailingZeros(Integer.highestOneBit(12)), which does return 3. Here is the Integer API
Some sample code:
numOfBytes = (Integer.numberOfTrailingZeroes(Integer.highestOneBit(integer)) + 8) / 8;
The + 8 is for proper rounding.
The lazy/inefficient way to do this is with Integer#toBinaryString. It will remove all leading zeros from positive numbers for you, all you have to do is call String#length and divide by 8.
Think about how to solve the same problem using normal decimal numbers. Then apply the same principle to binary / byte representation i.e. use 256 where you would use 10 for decimal numbers.
static int byteSize(long number, int bitsPerByte) {
int maxNumberSaveByBitsPerByte = // get max number can be saved by bits in value bitsPerByte
int returnValue = getFloor(number/maxNumberSaveByBitsPerByte); // use Math lib
if(number % maxNumberSaveByBitsPerByte != 0)
returnValue++;
return returnValue;
}
For positive values: 0 and 1 need 1 digit, with 2 digits you get the doubled max value, and for every digit it is 2 times that value. So a recursive solution is to divide:
public static int binaryLength (long l) {
if (l < 2) return 1;
else 1 + binaryLength (l /2L);
}
but shifting works too:
public static int binaryLength (long l) {
if (l < 2) return 1;
else 1 + binaryLength (l >> 1);
}
Negative values have a leading 1, so it doesn't make much sense for the question. If we assume binary1 is decimal1, binary1 can't be -1. But what shall it be? b11? That is 3.
Why you wouldn't do something simple like this:
private static int byteSize(int val) {
int size = 0;
while (val > 0) {
val = val >> 8;
size++;
}
return size;
}
int numOfBytes = (Integer.SIZE >> 3) - (Integer.numberOfLeadingZeros(n) >> 3);
This implementation is compact enough while performance-friendly, since it doesn't involve any floating point operation nor any loop.
It is derived from the form:
int numOfBytes = Math.ceil((Integer.SIZE - Integer.numberOfLeadingZeros(n)) / Byte.SIZE);
The magic number 3 in the optimized form comes from the assumption: Byte.SIZE equals 8