How do I check divisibility in Java? - java

I am trying to check if on number is divisible by another, and currently I use this method:
int x = 70;
int y = 30;
if(x/y == Math.round(x/y)) {
...
}
Is there a simpler way?

You can use modulus operator like this in your condition,
if (x%y == 0)

A good way is to use modulus operator, which returns the remainder after dividing by a number, e.g.
5 % 2 = 1 (1 is the remainder after 5 is divided by 2)
So for a number to be divisible by another, it should have a remainder of 0 (i.e. x % y = 0)
if (x % y == 0)
{
//x is divisible by y
}
else
{
//x is not divisible by y
}

Related

How to get the correct output in Modulo (10^9 + 7) format?

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 was trying to solve a Leetcode problem, regarding identifying if the number entered is a palindrome or not

I understood the logic behind the problem's solution, but in the coded solution I am a bit confused about the return statement in the end. Please explain to me what is its significance, why is it being used, etc ? (not why return is used but why is that value being returned).
class Solution {
public boolean isPalindrome(int x) {
// 2 cases x < 0 = false case
// x > 0 = test case
if (x < 0 || x % 10 == 0 && x != 0){
return false;
}
else {
int newNum = 0;
while (x > newNum){
int r = (x % 10);
newNum = newNum * 10 + r;
x /= 10;
}
//the part I am confused about - below
return x == newNum || x == newNum / 10;
}
}
}
So to understand the Logic for the return statement let us take 2 numbers
1234321
678876
So one thing here While loop is doing is to create a new number(newNum) out of X and making sure that newNum stores the reverse of X till the middle point.
So in case of 1234321 , this while loop will execute till X=123 and newNum=1234.
After exiting out from while loop with these values, out of the 2 statements in return, x == newNum / 10 will give true result hence return statement will return true.which means the number is palindrome.
Please note here that the no. digits in given integer is odd(7)
Let us now Take other example 678876
In this case when the while loop ends, the value for the X would be 678 and newNum would be 678
out of the 2 statements in return, x == newNum this time will give true result hence return statement will return true again .which means the number is palindrome.
Please note here that the no. digits in given integer is even(6)
All in all, this statement return x == newNum || x == newNum / 10;
is to make sure that we are covering the condition for both Odd and even no. of digits in the given integer X.

Find if int x is within 10 of closest hundred

Total noob question, but I am in my first Java class and working though a problem set. I know how to see if a number is in a specific range (posted below) but I am trying to find if this holds true of any of the nearest hundreds.
The rules are N has to be within 10 of either side of nearest 100.
if (n >= 90 && n <= 110) {
return true;
} else {
return false;
}
You can use % operator to calculate remainder of division.
int r = Math.abs(n) % 100; // use abs(), or r will be negative if n is negative
return r <= 10 || 90 <= r;

Java recursive method to find complement

I'm trying to think of how to use recursion to find complement of a number.
For example each digit x of a number must become 9 - x, so 1234 -> 8765.
I can't really think how to do that. This is my code so far:
public static int complement(int n){
int x = n % 10;
x = x - 9;
n = (n / 10)
return complement(n,x);
}
public static int complement(int n ,int times){
}
When you are dealing with recursion, it is important to write the algoritm first in English (or your native tongue :) ).
For this task, consider the following:
I have an number n. Let's take the last digit and subtract this digit to 9.
Do this again for the rest of the digits, i.e. n / 10. With the result obtained, we need to make a number again: so we multiply the result by 10 and add the digit we calculated before. In other words, complement(n / 10) returns the complement of the number n without the last digit, so we need to append the complement of the last digit to this.
When the number is less than 10, we have nothing more to do and we can just return 9 - n (this is the base case, the number is only one digit long).
In code, this is implemented as:
public static int complement(int n) {
if (n < 10) {
return 9 - n;
}
int x = n % 10;
x = 9 - x;
return 10 * complement(n / 10) + x;
}
and then:
System.out.println(complement(1234)); // prints 8765
This can be written a bit shorter with:
public static int complement(int n) {
if (n < 10) {
return 9 - n;
}
return 10 * complement(n / 10) + 9 - n % 10;
}

Why do I get -1 from this statement?

if(heading == 2){
nextY = (y-1) % 20;
nextX = x;
}
When debugging this program, my heading is 2 and y = 0, however, when I come to this if statement, nextY becomes -1. Why is it not cycling properly? (0-19)?
That's how mod operation generally works for negative numbers in programming (in all languages I tried it in).
But you can easily make number positive before doing mod
nextY = (y + 20 - 1) % 20;
Modulo operators often return negative numbers for negative inputs. For example, C# will give you a number from -356..359 for the expression x % 360.
Instead of subtracting 1 then taking modulo 20, you can add 19, which is the same thing but keeps the number positive, or you can use the ternary operator:
nextY = (y+19) % 20; // or
nextY = (nextY == 0) ? 19 : nextY - 1;

Categories