I was working on a problem on LeetCode that asks the question: determine whether an integer is a palindrome without converting the integer into a string. I am able to come up with my own algorithm to determine a palindrome but couldn't come up with one without converting the integer to a string. So I ran into this code on the Internet:
public boolean isPalindrome(int x) {
if (x < 0)
return false;
// initialize how many zeros
int div = 1;
while (x / div >= 10) {
div = div * 10;
}
while (x != 0) {
int left = x / div;
int right = x % 10;
if (left != right)
return false;
x = (x % div) / 10;
div = div / 100;
}
return true;
}
I step through the code several times to see what it was doing but I am having such a hard time understanding how this person was able to come up with this logic. Now, I know how division and modulo works. However, this part is fuzzy:
// initialize how many zeros
int div = 1;
while (x / div >= 10) {
div = div * 10;
}
I believe this person is trying to determine the decimal place?
The next snippet part of their code, I'm completely baffled as to how they came up with this. I mean ... is this some simple math trick that I'm obviously not coming up with an explanation? In simple terms, what are they doing here? How did they decide on the divisor of 10 and 100?
x = (x % div) / 10;
div = div / 100;
I appreciate any explanation to help me understand. Thanks in Advance.
v/r,
Allen
Let's take x=12321
Then
int div = 1;
while (x / div >= 10) {
div = div * 10;
}
above part makes div = 10000,
then this part makes left = 1 and right = 1, and then left and right are compared
int left = x / div;
int right = x % 10;
Then, as we move through this part
x = (x % div) / 10;
div = div / 100;
this occurs
x = (12321%10000)/10 = (2321)/10 = 232
They modulo with div, to get rid of the first digit and then they divide by 10 to remove the last digit. The first and the last digits are removed because they have already been compared. The div is divided by 100, because we remove 2 digits from 'x' at a time...the first digit and the last digit.
now, x = 232
This part makes left = 2 and right = 2, and again left and right are compared
int left = x / div;
int right = x % 10;
then, as we move through this part
x = (x % div) / 10;
div = div / 100;
this occurs
x = (232%100)/10 = (32)/10 = 3
After this, left = 3 and right = 3, they match, 'true' is returned and the loop ends.
private static boolean isPalindrome(int number) {
int temp = number;
int result = 0;
while (temp != 0) {
result = result * 10 + temp % 10;
temp /= 10;
}
return number == result;
}
Related
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;
Given an integer A representing the square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. Find and return the maximum height of the staircase.
Your submission failed for the following input: A : 92761
Your function returned the following : 65536
The expected returned value : 430
Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…
Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.
CODE
public int solve(int A) {
int l=1,h=A,T=2*A;
while(l<=h)
{
int mid=l+(h-l)/2;
if((mid*(mid+1))==T)
return mid;
if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
return mid-1;
if((mid*(mid+1))>T)
h=mid-1;
else
l=mid+1;
}
return 0;
}
To expand on the comment by Matt Timmermans:
You know that for n steps, you need (n * (n + 1))/2 blocks. You want know, if given B blocks, how many steps you can create.
So you have:
(n * (n + 1))/2 = B
(n^2 + n)/2 = B
n^2 + n = 2B
n^2 + n - 2B = 0
That looks suspiciously like something for which you'd use the quadratic formula.
In this case, a=1, b=1, and c=(-2B). Plugging the numbers into the formula:
n = ((-b) + sqrt(b^2 - 4*a*c))/(2*a)
= (-1 + sqrt(1 - 4*1*(-2B)))/(2*a)
= (-1 + sqrt(1 + 8B))/2
= (sqrt(1 + 8B) - 1)/2
So if you have 5050 blocks, you get:
n = (sqrt(1 + 40400) - 1)/2
= (sqrt(40401) - 1)/2
= (201 - 1)/2
= 100
Try it with the quadratic formula calculator. Use 1 for the value of a and b, and replace c with negative two times the number of blocks you're given. So in the example above, c would be -10100.
In your program, since you can't have a partial step, you'd want to truncate the result.
Why are you using all these formulas? A simple while() loop should do the trick, eventually, it's just a simple Gaussian Sum ..
public static int calculateStairs(int blocks) {
int lastHeight = 0;
int sum = 0;
int currentHeight = 0; //number of bricks / level
while (sum <= blocks) {
lastHeight = currentHeight;
currentHeight++;
sum += currentHeight;
}
return lastHeight;
}
So this should do the job as it also returns the expected value. Correct me if im wrong.
public int solve(int blocks) {
int current; //Create Variables
for (int x = 0; x < Integer.MAX_VALUE; x++) { //Increment until return
current = 0; //Set current to 0
//Implementation of the Gauss sum
for (int i = 1; i <= x; i++) { //Sum up [1,*current height*]
current += i;
} //Now we have the amount of blocks required for the current height
//Now we check if the amount of blocks is bigger than
// the wanted amount, and if so we return the last one
if (current > blocks) {
return x - 1;
}
}
return current;
}
I was wondering if anyone knew how to use mathematics to truncate a number from the left (remove digits one by one starting from the left).
I can use a simple division to truncate digits from the right:
int num = 10098;
while (num > 0){
System.out.println(num);
num /= 10;
}
This will output what I want:
10098
1009
100
10
1
But does anyone know a way to do this the other way around on integers and to truncate digits from the left without converting to String?
Try n = n % (int) Math.pow(10, (int) Math.log10(n));. Found here.
public void test() {
int n = 10098;
while (n > 0) {
System.out.println("n=" + n);
n = n % (int) Math.pow(10, (int) Math.log10(n));
}
}
prints
n=10098
n=98
n=8
int in = ...;
//the first number n : 10^n > in
int mostSignificantDigit = 1;
int digits = 1;
while(mostSignificantDigit < in)
{
mostSignificantDigit *= 10;
digits++;
}
//create the numbers
int[] result = new int[digits];
int count = 0;
while(mostSignificantDigit != 0){
result[count] = in % mostSignificantDigit;
mostSignificantDigit /= 10;
}
You can use the module operation %. The module is the remainder of the division.
You have to call it with with power of 10. So 10, 100, 1000, 10000
You can do it
int num = 10098;
int divided = num;
int module = 1;
while (divided > 0) {
divided /= 10;
module *= 10;
System.out.println(num % module);
}
Please note that if you don't left padding with zeros you will obtain 98 instead of 0098 or 098.
For an assignment I must create a method using a binary search to find the square root of an integer, and if it is not a square number, it should return an integer s such that s*s <= the number (so for 15 it would return 3). The code I have for it so far is
public class BinarySearch {
/**
* Integer square root Calculates the integer part of the square root of n,
* i.e. integer s such that s*s <= n and (s+1)*(s+1) > n
* requires n >= 0
*
* #param n number to find the square root of
* #return integer part of its square root
*/
private static int iSqrt(int n) {
int l = 0;
int r = n;
int m = ((l + r + 1) / 2);
// loop invariant
while (Math.abs(m * m - n) > 0) {
if ((m) * (m) > n) {
r = m;
m = ((l + r + 1) / 2);
} else {
l = m;
m = ((l + r + 1) / 2);
}
}
return m;
}
public static void main(String[] args) {
//gets stuck
System.out.println(iSqrt(15));
//calculates correctly
System.out.println(iSqrt(16));
}
}
And this returns the right number for square numbers, but gets stick in an endless loop for other integers. I know that the problem lies in the while condition, but I can't work out what to put due to the gap between square numbers getting much bigger as the numbers get bigger (so i can't just put that the gap must be below a threshold). The exercise is about invariants if that helps at all (hence why it is set up in this way). Thank you.
Think about it: Math.abs(m*m-n) > 0 is always true non-square numbers, because it is never zero, and .abs cannot be negative. It is your loop condition, that's why the loop never ends.
Does this give you enough info to get you going?
You need to change the while (Math.abs(m * m - n) > 0) to allow for a margin of error, instead of requiring it be exactly equal to zero as you do right now.
Try while((m+1)*(m+1) <= n || n < m * m)
#define EPSILON 0.0000001
double msqrt(double n){
assert(n >= 0);
if(n == 0 || n == 1){
return n;
}
double low = 1, high = n;
double mid = (low+high)/2.0;
while(abs(mid*mid - n) > EPSILON){
mid = (low+high)/2.0;
if(mid*mid < n){
low = mid+1;
}else{
high = mid-1;
}
}
return mid;}
As you can see above , you should simply apply binary search (bisection method)
and you can minimize Epsilon to get more accurate results but it will take more time to run.
Edit: I have written code in c++ (sorry)
As Ken Bloom said you have to have an error marge, 1. I've tested this code and it runs as expected for 15. Also you'll need to use float's, I think this algorithm is not possible for int's (although I have no mathematical proof)
private static int iSqrt(int n){
float l = 0;
float r = n;
float m = ((l + r)/2);
while (Math.abs(m*m-n) > 0.1) {
if ((m)*(m) > n) {
r=m;
System.out.println("r becomes: "+r);
} else {
l = m;
System.out.println("l becomes: "+l);
}
m = ((l + r)/2);
System.out.println("m becomes: "+m);
}
return (int)m;
}
So I need to do modulo exponentiation using 2^N mod M, but I cant use % or any built in java.math or Math method. Applying mod M as 2^N increases seems* like it would work. But is doesn't seem to ( or im just doing it wrong...)
int N = 63;
int M = 1000;
int result;
while (n > 0)
{
power *= 2;
n --;
// this part defn doesnt work... best idea so far
if (power >M)
{
result = power - m;
}
}
Per §15.17.3 "Remainder Operator %" of The Java Language Specification, Java SE 7 Edition, (a/b)*b+(a%b) is always equal to a. Turning this around, we have a%b == a - (a/b)*b. So, you should be able to write:
power *= 2;
power -= (power/M) * M;
Or, since you're only multiplying by two each time, you know that power cannot exceed M before this operation, so you can rewrite the above as:
power *= 2;
if (power > M) {
power -= M;
}
Maybe power -= m instead of result = power - m?
Since BigInteger.modPow already implements this, you should just look at the source code of BigInteger.
Annotated code:
int M = 13;
int result = 2;
int n = 10;
while (--n > 0) // do n iterations multiplying the number with 2
result *= 2;
if (M < 0) // safe guard if someone gives you a negative M then flip it
M *= -1;
while ((result-M) >= 0) // keep subtracting M until right before it turns negative
result -= M;
Remember though, that integers are not big enough for 2^63 like your code shows you're trying to do. ints are 32 bit signed, so 2^31 to -2^31-1 is the range.
Your version seems also to do modulus on each iteration of multiplication. You can do that, too. And it will allow you to use 2^63 like your code tries:
int M = 13;
int result = 2;
int n = 10;
if (M < 0)
M *= -1;
while (--n > 0) {
result *= 2;
while ((result-M) >= 0)
result -= M;
}
Assumptions: power and modulo > 0, a validation should be in place before calling this method.
long modPow(long x, long power, long modulo) {
if (power > 1) {
x = modPow(x, power / 2, modulo) * modPow(x, (power + 1) / 2, modulo);
}
return x - x / modulo * modulo;
}
call it:
result = modPow(2, power, modulo);
Here is a recursive version. If power is too big to handle it, we split it in 2. We then return x % modulo(inspired by "ruakh example"). We also know that:
y = y / 2 + (y + 1) / 2
so
x^n = x^(n/2) * x^[(n+1)/2]
This way, we know that every modPow call will return a number smaller than modulo every time.
Advantages? Parallelization and if you want to make things even fancier, add memoisation.
You can easily convert my version in a Fork / Join model, you can find more details about it here
Haven't you noticed that it is the power of 2 ? Why hadn't you used it?
2^N mod M is to be counted as
long power=1L << N;
long temp=power/M;
long result= power-temp*M;
You can just use power-=M as the modulo is nothing but continuous subtraction of the divisor from divident until the divident<divisor.
The below should work
public class HelloWorld{
public static void main(String []args){
int N = 63;
int M = 1000;
long result=0;
long power=1;
for(int i=0;i<N;i++)
{
power *= 2;
N--;
if (power >=M)
{
power = power - M;
}
}
System.out.println("power:"+power);
}
}