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.
Related
New to Stackoverflow so please point out anything I can do to improve the quality of my question.
So what my code does (or rather hopes to do) is calculate huge fibonacci numbers modulo a pretty huge m. To make the algorithm more efficient, I employ the use of pisano periods. In essence, I calculate the pisano period of m and then make the calculation of the remainder easier by using the following relation:
The remainder of the n th Fibonacci number (modulo m) is equal to the remainder of the k th Fibonacci number (modulo m) such that k = n % p where p is the pisano period of m.
In order to calculate the pisano period, I use the following property:
If the current Fib % m = 0 and the sum of all Fib's until now % m = 0, then the index of the current Fib is the pisano period of m. (Note the index must be greater than 0)
However I run into a problem in this endeavour: To calculate the pisano period, I have to calculate consecutive Fibonacci numbers. The issue arises when the number of Fibonacci numbers that have to be calculate becomes very large, say 100 000. Then the data type long overflows.
To my knowledge, any endeavour to calculate pisano periods will require the calculation of fibonacci's, so the only solution seems to be to replace long with something else. If anyone has any suggestions as to what this replacement might be, I would greatly appreciate it.
import java.util.*;
public class FibHuge {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
long num = in.nextLong ();
long mod = in.nextLong();
System.out.println ( getMod(num, mod));
}
private static int getMod (long num, long mod) {
Period per = new Period();
long period = per.getPeriod (mod);
int newFibNum = (int)(num % period);
num = (num % mod);
Integer ia[] = new Integer [per.al.size()];
ia = per.al.toArray (ia);
return ia[newFibNum];
}
}
class Period {
ArrayList <Long> al;
long FNum;
long SNum;
Period () {
al = new ArrayList <Long> ();
FNum = 0;
SNum = 1;
}
private long getFib (long first, long second){
return first + second;
}
long getPeriod (long mod){
boolean bool = true;
long fibcount = 0;
long currentmod = 0;
long fib = 0;
long sum = 0;
while (bool){
if (fibcount <= 1){
currentmod = fibcount % mod;
al.add (currentmod);
sum += fibcount;
}
else {
fib = getFib (FNum, SNum);
FNum = SNum;
SNum = fib;
currentmod = (fib % mod);
al.add (currentmod);
sum += fib;
}
if ( (currentmod == 0 & (sum % mod) == 0) & fibcount > 0){
return fibcount;
}
fibcount++;
}
return mod; //essentially just to satisfy the return condition
}
}
Use BigInteger, but take note that it will be much slower, but with infinite size.
You don't need to use BigInteger unless your modulus is too large to fit into a long in which case I suspect you will run out of memory trying to find the solution.
Instead of calculating the n-th Fibonacci number and then performing a modulus, you can calculate the n-th Fibonacci after modulus using this property
(a + b) % n = (a % n + b % n) % n;
In other words you only need to keep adding the modulus of the number in each iteration. You can save all the modulus values in a Set and when you get a repeated result, you have a period. You can store the iteration number with the result and use this to calculate the period.
In fact modulus is kind of expensive but since you will only ever sum a number which is less than 2 * modulus you can simply do
long c = a + b; // Fibonacci
if (c >= modulus) c -= modulus; // the only real change you need for modulus.
As Java uses a condition move rather than an actual branch this is much faster than using %
I can't think of much more details you need to know without writing the code for you.
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);
}
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
I need to work out a very large power modulo (2^32), i.e. I want the result of:
y = (p^n) mod (2^32)
p is a prime number
n is a large integer
Is there a trick to doing this efficiently in Java?
Or am I stuck with doing it in a loop with n iterations?
The simple way to mod 2^32 is to use & 0xFFFFFFFFL. Also, there happens to be a type which naturally keeps the lowest 32-bit called int ;) If you use that you don't even need to perform the & until you have the result (so the answer is unsigned) For this reason you only need to keep the last 32 bit of the answer. To speed up the ^n you can calculate the square, it's square and it's square etc, e.g if n is 0b11111 then you need to multiply p^16 * p^8 * p^4 * p^2 * p.
In short, you can use plain int as you only need 32-bit of accuracy and values with a cost of O(ln n) where n is the power.
int prime = 2106945901;
for (int i = 0; i < 10; i++) {
long start = System.nanoTime();
long answer1 = BigInteger.valueOf(prime)
.modPow(
BigInteger.valueOf(prime),
BigInteger.valueOf(2).pow(32)).longValue();
long mid = System.nanoTime();
int answer2 = 1;
int p = prime;
for (int n = prime; n > 0; n >>>= 1) {
if ((n & 1) != 0)
answer2 *= p;
p *= p;
}
long end = System.nanoTime();
System.out.printf("True answer %,d took %.3f ms, quick answer %,d took %.3f ms%n",
answer1, (mid - start) / 1e6, answer2 & 0xFFFFFFFFL, (end - mid) / 1e6);
}
prints finally
True answer 4,169,684,317 took 0.233 ms, quick answer 4,169,684,317 took 0.002 ms
You can utilize exponentiation by squaring. Firstly, break it down into powers of two for your given n. Since p^n (mod x) == p^(k1) (mod x) . p^(k2) (mod x) . ... p^(kn) (mod x) where sum k_i = n, you can utilize this and successive powers of two to calculate this in O(log n) steps.
In addition to the other answers you can use some elementary number theory to reduce the time needed to compute an mod 232 for a an odd integer to O(1). The Euler Phi function together with Euler's Theorem allows you to discard all but the low-order 31 bits of n.
φ(232) = 231, and aφ(232) = 1 mod 232.
Thus if n = q*(231) + r, 0 <= r < 231, then an mod 232 = ar mod 232
r is simply the low-order 31 bits of n, i.e. n & 0x7fffffff. In fact, by Carmichael's Theorem you can do a bit better (literally), and you only need to consider the low-order 30 bits of n, i.e. n & 0x3fffffff. You can precompute these once and store them in a table of size 4GB for a given base a. Here is some java code as an example.
import java.math.BigInteger;
public class PowMod2_32 {
private static final long MASK32 = 0xffffffffL;
public static long pow32(final int a, final int exponent)
{
int prod = 1;
for (int i = 29; i>=0; i--) {
prod *= prod; // square
if (((exponent >> i) & 1) == 1) {
prod *= a; // multiply
}
}
return prod & MASK32;
}
public static long pow32(BigInteger a, BigInteger exponent) {
return pow32(a.intValue(), exponent.intValue());
}
}
There are no tricks in java that I know of but rather there are some tricks in maths.
If you implement these as an algorithm it should speed up computation.
Look at 5 and 6. Look at 4 also if power of two is always even
Use the Class Bigintiger. here´s an example how to work / pow with it
public String higherPow() {
BigIntiger i = new Bigintger("2");
// doing a power(2^32)
i = i.pow(32);
// after 2^32 was made, do mod 100
i = i.mod(new Bigintiger("100"));
return i.toString();
}
(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();