Create a method names dividesEvenly(a,b) that can receive two integers, a and b, return true if a can be divided evenly by b. Return false otherwise.example : dividesEvenly(8, 4) ➞ true # 8/4 = 2 dividesEvenly(10, 2) ➞ false # 10/2 = 5
This question is about the modulus operator, in java a % symbol, also known as the remainder operator.
See also the documentation
If "a" can be divided evenly by "b", the result of a / b will be an even number. You can then check this with a modulus operation.
Writing this as a method in java, you have
public boolean dividesEvenly(int a, int b) {
int division = a / b;
return division % 2 == 0;
}
These two steps are summarized as follows:
Divide a by b and assign this value to a variable (called "division" in the code)
Check that if this division were divided by two it would have no remainder (division mod 2 equals zero). If this is the case, then it divides evenly. Otherwise (division mod 2 not zero) the result of the division is an odd number.
I think you are looking for the modulo % opperator. To check whether a number, in your case a/b, is even you can do this: (a/b)%2 == 0
The complete methode would lock something like this:
public boolean dividesEvenly(int a, int b) {
return (a/b)%2==0;
}
Related
I am given with three integers A, B and C. I need to implement a program to perform the operation A^B modulus C.
I without thinking much, wrote the following code:-
public int Mod(int A, int B, int C)
{
return (int)Math.pow(A,B) % C;
}
testcase : A = -1, B = 1, C = 20, the expected o/p was 19 whereas my code gave -1 as output.
I found out that this approach is incorrect when there is a negative number, in this example, when A < 0.
I referred to explanations in few websites, but was unable to understand this behavior.
Please help me on this one. Thank you.
% Operator in Java
In java, when calculating
A % B
the answer is produced according to following conditions:
When the dividend is negative, the answer produced will also be negative and when the dividend is positive, the answer produced will also be positive.
Do note that this behavior is language specific. In python, the above program will produce 19 as output.
Flaw in the code
If one only wants A % B to produce positive results, then simply using A % B will produce wrong output because of reasons mentioned above.
Also, calculating A^B % C where B can take large values directly is not the right approach. I suggest you use fast exponentiation to do so. It is a famous algorithm and you can easily find it online.
Solution
If you want only positive result, use this:
r = a % b > 0 ? a % b : Math.abs(b) + a % b;
Here r is remainder, a is dividend and b is divisor.
I hope I have helped you. If you want to understand why this happens, do comment and I will be happy to edit my answer to help you.
There is no 'modulus' operator in Java; there is a remainder operator.
Negative one to the power one is negative one.
The remainder of dividing negative one by 20 is negative one.
The JLS (link above) specifically says that the sign of the result is the same as the sign of the left-hand side. Thus -1 and not +19.
The definition of % is
The remainder operation for operands that are integers after binary
numeric promotion (§5.6.2) produces a result value such that
(a/b)*b+(a%b) is equal to a.
function pow(A,B,C)
{
if(A == 0) {
return 0;
}
else if(B == 0) {
return 1;
}
else if(B%2 == 0) {
let half = this.power(A,Math.floor(B/2),C);
return (half * half)%C;
}
else {
return ((this.power(A,B-1,C)) * A%C)%C;
}
}
For example, (-3) % 2 will return -1 instead of 1.
What is the preferred way to get the positive remainder in Scala? Such as (((-3) % 2) + 2) % 2, or abs(-3 % 2)?
In scala, why could remainder (%) operator return a negative number?
There are different conventions for the sign of the result of a modulo operation; Wikipedia has a good article on it. Scala, like most but by no means all programming languages, has the result take the sign of the dividend (the -3 in your case).
What is the preferred way to get the positive remainder in Scala?
I doubt there's a generally-agreed preferred way; if it were me, either use Math.floorMod, which gives a result with the sign of the divisor (2 in your example) instead of the dividend (this doesn't just mean the same value as % with a different sign, see the linked JavaDoc for details). Or just an if afterward (if (result < 0) { result += M; } [where M is the divisor, 2 in your example]).
The correct way to get the positive modulus is to add the divisor to the negative modulus:
(-18 % 5) + 5
Taking the absolute value will give you the wrong solution in this case, though it will work if the divisor happens to be 2.
If you don't know the sign of the dividend, you can do something like this:
((dividend % divisor) + divisor) % divisor
Using math.abs(-x % y) does not usually yield the same behavior as returning a positive modulus:
scala> math.abs(-7 % 3)
res46: Int = 1
But that's not what python (a language that returns a positive modulus) says:
In [14]: -7 % 3
Out[14]: 2
If we look at increments of 3 from -7:
-7, -4, -1, 2, ..
scala stops at -1, and python stops at 2.
I would like to add something to the existing answers. My preferred way to get the positive remainder is to add a new method to the Int type as follows:
object Extensions
{
implicit class ExtendedInt (val i: Int) extends AnyVal {
def positiveMod (m: Int) = {val x = i % m; if (x < 0) x + m else x}
}
}
In the file where you want to use the method, import the implicit class with:
import Extensions._
Now you can do:
(-3).positiveMod(2)
You could also put the implicit class in a package object so you don't need to import when calling the function from the same package.
For example, if you want to filter out all odd elements from an array, ignoring negative or positive, you can do like this:
arr.filter{x => Math.abs(x%2)==1}
I need to do a MOD of a number which is a long datatype with 1965.
Something like this -
number % 1965
Will the above modulus result always be within 0 and 1964?
Or there are some cases in which it won't return any number between 0 and 1664?
I am using Java as programming language and I will be running my program on Ubuntu machines.
Initially I thought its a Math question but it depends mostly on the Compiler and Language... So kind of confused it will always return number between 0 and 1664 or there are some exception cases?
This is what I have in my method -
private static int getPartitionNumber() {
return (int) (number % 1965);
}
UPDATE:
One thing I forgot to mention is, here number will always be positive number. Any negative number I am throwing IllegalArgumentException at the starting of the program.
No, java's implementation of modulus will return a value in the range (-n, n) for the value x % n. I.e. If you have a negative number as the left operand, then the result will be negative. to get around this, try something like the following:
((x % n) + n) % n;
Which will return a value in the range [0,n)
EDIT (to reflect UPDATE in question)
In the case of positive numbers in the left operand, then simply x % n will produce numbers in the range [0,n) where x >= 0.
Here's my implementation of Fermat's little theorem. Does anyone know why it's not working?
Here are the rules I'm following:
Let n be the number to test for primality.
Pick any integer a between 2 and n-1.
compute a^n mod n.
check whether a^n = a mod n.
myCode:
int low = 2;
int high = n -1;
Random rand = new Random();
//Pick any integer a between 2 and n-1.
Double a = (double) (rand.nextInt(high-low) + low);
//compute:a^n = a mod n
Double val = Math.pow(a,n) % n;
//check whether a^n = a mod n
if(a.equals(val)){
return "True";
}else{
return "False";
}
This is a list of primes less than 100000. Whenever I input in any of these numbers, instead of getting 'true', I get 'false'.
The First 100,008 Primes
This is the reason why I believe the code isn't working.
In java, a double only has a limited precision of about 15 to 17 digits. This means that while you can compute the value of Math.pow(a,n), for very large numbers, you have no guarantee you'll get an exact result once the value has more than 15 digits.
With large values of a or n, your computation will exceed that limit. For example
Math.pow(3, 67) will have a value of 9.270946314789783e31 which means that any digit after the last 3 is lost. For this reason, after applying the modulo operation, you have no guarantee to get the right result (example).
This means that your code does not actually test what you think it does. This is inherent to the way floating point numbers work and you must change the way you hold your values to solve this problem. You could use long but then you would have problems with overflows (a long cannot hold a value greater than 2^64 - 1 so again, in the case of 3^67 you'd have another problem.
One solution is to use a class designed to hold arbitrary large numbers such as BigInteger which is part of the Java SE API.
As the others have noted, taking the power will quickly overflow. For example, if you are picking a number n to test for primality as small as say, 30, and the random number a is 20, 20^30 = about 10^39 which is something >> 2^90. (I took the ln of 10^39).
You want to use BigInteger, which even has the exact method you want:
public BigInteger modPow(BigInteger exponent, BigInteger m)
"Returns a BigInteger whose value is (this^exponent mod m)"
Also, I don't think that testing a single random number between 2 and n-1 will "prove" anything. You have to loop through all the integers between 2 and n-1.
#evthim Even if you have used the modPow function of the BigInteger class, you cannot get all the prime numbers in the range you selected correctly. To clarify the issue further, you will get all the prime numbers in the range, but some numbers you have are not prime. If you rearrange this code using the BigInteger class. When you try all 64-bit numbers, some non-prime numbers will also write. These numbers are as follows;
341, 561, 645, 1105, 1387, 1729, 1905, 2047, 2465, 2701, 2821, 3277, 4033, 4369, 4371, 4681, 5461, 6601, 7957, 8321, 8481, 8911, 10261, 10585, 11305, 12801, 13741, 13747, 13981, 14491, 15709, 15841, 16705, 18705, 18721, 19951, 23001, 23377, 25761, 29341, ...
https://oeis.org/a001567
161038, 215326, 2568226, 3020626, 7866046, 9115426, 49699666, 143742226, 161292286, 196116194, 209665666, 213388066, 293974066, 336408382, 376366, 666, 566, 566, 666 2001038066, 2138882626, 2952654706, 3220041826, ...
https://oeis.org/a006935
As a solution, make sure that the number you tested is not in this list by getting a list of these numbers from the link below.
http://www.cecm.sfu.ca/Pseudoprimes/index-2-to-64.html
The solution for C # is as follows.
public static bool IsPrime(ulong number)
{
return number == 2
? true
: (BigInterger.ModPow(2, number, number) == 2
? (number & 1 != 0 && BinarySearchInA001567(number) == false)
: false)
}
public static bool BinarySearchInA001567(ulong number)
{
// Is number in list?
// todo: Binary Search in A001567 (https://oeis.org/A001567) below 2 ^ 64
// Only 2.35 Gigabytes as a text file http://www.cecm.sfu.ca/Pseudoprimes/index-2-to-64.html
}
BigInteger bigInteger = ...;
if(bigInteger.longValue() > 0) { //original code
//bigger than 0
}
//should I change to this?
if(bigInteger.compareTo(BigInteger.valueOf(0)) == 1) {
//bigger than 0
}
I need to compare some arbitary BigInteger values. I wonder which approach is correct. Given the above code which one should be used? The original code is on the top.. I am thinking to change it to the second approach.
The first approach is wrong if you want to test if the BigInteger has a postive value: longValue just returns the low-order 64 bit which may revert the sign... So the test could fail for a positive BigInteger.
The second approach is better (see Bozhos answer for an optimization).
Another alternative: BigInteger#signum returns 1 if the value is positive:
if (bigInteger.signum() == 1) {
// bigger than 0
}
If you are using BigInteger, this assumes you need bigger numbers than long can handle. So don't use longValue(). Use compareTo. With your example it better be:
if (bigInteger.compareTo(BigInteger.ZERO) > 0) {
}
This is not a direct answer, but an important note about using compareTo().
When checking the value of compareTo(), always test for x < 0, x > 0 and x == 0.
Do not test for x == 1
From the Comparable.compareTo() javadocs:
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Note:
A negative integer, not -1.
A positive integer, not 1.
True, checking for ==1 and ==-1 would work for BigInteger. This is the BigInteger.compareTo() code:
public int compareTo(BigInteger val) {
if (signum == val.signum) {
switch (signum) {
case 1:
return compareMagnitude(val);
case -1:
return val.compareMagnitude(this);
default:
return 0;
}
}
return signum > val.signum ? 1 : -1;
}
But it's still bad practice, and explicitly recommended against in the JavaDocs:
Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.