Find repeating bit sequence in number - java

How can I find multiples of a given bit sequence?
So the code should work like this:
int bit = 0b100
for (int i = 0; i<=50;i++){
if (bit in i){
print(i);
}
}
This should print 4 (100) and 36 (100100).
I was trying to iterate through it and bit-mask it but it also printed numbers like 40 (101000).
So it should only print numbers containing only multiplies of that sequence (100, 100100, 100100100 ...) but not numbers like 1100, 1001001 ...

You can use the modulo operator and shift operator to check the lower bits of the number and "reduce" the incoming number to check the next lower bits of the remaining number. The algorithm works like this:
Do a modulo of the sequence on the number to check. The modulo must be 0.
So when you have the sequence 0b100 and you have a number to check like 0bXXXXXXXX101 the modulo would be 0b001, which is not 0 and you know the number can't be a sequence of multiple 0b100s.
Shift the remaining number to the right, since you have already checked the first N bits on the right.
You shift the number with the >> operator. This will move the bits to the right, dropping the already checked bits:
0bXXXXXXXX101
0bXXXXXXXX (shifted to the right)
The tricky part is to calculate how big the shift is. You can use log2() to figure that out. When you completed the shift, you go back to point 1 above.
The complete code can look like this:
public static boolean isMultipleOfSequence(int sequence, int number) {
if (sequence == 0) {
return number == 0;
}
while (number != 0) {
int remaining = number % sequence;
if (remaining != 0) {
return false;
}
int shift = log2(sequence);
number = number >> shift;
}
return true;
}
public static int log2(int value) {
return Integer.SIZE-Integer.numberOfLeadingZeros(value);
}
When you try it with the following code:
System.out.println(isMultipleOfSequence(0b100, 0b100));
System.out.println(isMultipleOfSequence(0b100, 0b100100));
System.out.println(isMultipleOfSequence(0b100, 0b100100100));
System.out.println(isMultipleOfSequence(0b100, 0b101100100));
System.out.println(isMultipleOfSequence(0b100, 0b100110100));
System.out.println(isMultipleOfSequence(0b101, 0b101101101));
System.out.println(isMultipleOfSequence(0b101, 0b100101101));
You will get the following output:
true
true
true
false
false
true
false
You might need to check for negative inputs as this method only works for positive numbers.

I'm not sure how to do it with pure math, but regex works:
Pattern pattern = Pattern.compile("^(100)+$");
for (int i = 0; i < 100; i++) {
String binary = Integer.toBinaryString(i);
if (pattern.matcher(binary).find()) {
System.out.println(i + " " + binary);
}
}
Edit: What about going the other direction?
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10; i++) {
builder.append("100");
System.out.println(Integer.parseInt(builder.toString(), 2));
}

Related

How to sum consecutive equal digits in a number in Java

The following question was asked in my last interview (yesterday), and I'm trying to solve it since then (couldn't solve it in the interview).
Sorry for any grammar mistakes or any logical mistakes, I don't have the question, it was written by memory:
You are given a number in a string format, for example: "14438832066".
You got to sum up the consecutive equal digits in that number. If no
consecutive equal digit was found, just add the digit to the result.
for example: solution(19938832066) => 11831632012
Explanation: first digit is 1.
The second and third digits are both 9 which means they will turn into 18 in the result string.
So on
with the rest of the digits (as you can see, the last 2 digits are both 6 which means they will turn into 12 in the result string).
You are required to do that for the result string as well, if needed, until no equal consecutive digits are found in the number.
Example:: number: 14438832066 solution( "19938832066") ->"11831632012" -> "2831632012"
Explanation: first result is 11831632012, but then you can see that there are still equal consecutive digits : the first and the
second digits are both 1. So process that number as well.
You are given a string and must return a string.
My solution:
I couldn't write the solution, I don't know why. It's a pretty simple question, I thought going recursive at first but didn't want to complex things.
I wrote 2 helper methods:
one that returns a boolean whether the number consists of equal consecutive digits.
one that actually makes the business logic:
turn the string into a char array
create a counter that will count instances of the same digit - (int counter = 1).
loop on the array from the first to the one before the last element :
inside the loop:
//equal digit was found - increment counter and continue to next digit
if char[i] == char[i+1] then counter++
//calculation in case we are done counting the same digit
else if counter > 0 then result.append(counter*digit[i])
// if no consecutive equal digit was found
else result.append(digit[i])
end loop: return result
Problems I had:
I created the counter inside the loop, so each iteration it got rested. took me few minutes to realize.
I had troubles realizing that 'int(digit[i])' doesn't give me the numeric value of the char, it gives the ASCII value. I had to use "Character.getNumericValue" (don't remember the exact name of the method).
Because of these problems, it took me 45 minutes to write the solution which in the end didn't even work.
I'll be glad to get a working solution, and even better - to get any feedback and tips on my solution and what, in your opinion, were my mistakes.
Thank you.
Your pseudo-code seems alright, as far as it goes. What's missing is that you don't repeatedly check the result string to see if another pass is required. I also show how you don't need to remember the API to convert a character to a digit; if you know the digits are decimal, you can interpret them yourself. As an interviewer, I would accept that there is an API that you can't precisely remember or your home-brew solution as equally valid.
String transform(String number) {
while (true) {
String result = collapse(number);
if (result.equals(number)) return result;
number = result;
}
}
private static String collapse(String number) {
StringBuilder result = new StringBuilder();
for (idx = 0; idx < number.length(); ) {
int mark = idx;
int digit = digitAt(number, idx++);
while (idx < number.length() && digitAt(number, idx) == digit) ++idx;
result.append((idx - mark) * digit);
}
return result.toString();
}
private static int digitAt(String num, int index) {
char ch = number.charAt(index);
if (ch < '0' || ch > '9') throw new IllegalArgumentException();
return ch - '0';
}
The preceding is a naïve approach that transforms the string until there are no changes. I suspect there might be a more "elegant" approach that works from left to right through the input in a single pass, but it would take some thought, and I probably couldn't come up with that in an interview.
Here's an algorithm that uses recursion and a for-loop to add consecutive equal digits. I think the code is pretty self-explanatory but please ask if you have any queries.
public static String addConsecutiveDigits(String number) {
char[] arr = number.toCharArray();
StringBuilder result = new StringBuilder();
boolean foundConsecutive = false; // boolean flag for checking if the number contained consecutive equal digits
for (int i = 0; i < arr.length; i++) {
int digit = arr[i] - '0'; //Subtracting ascii values to get integer values
int newNumber = digit;
if (i != arr.length - 1) {
int nextDigit = arr[i + 1] - '0';
if (digit == nextDigit) { // check if the digits are consecutive digits
newNumber = digit + nextDigit;
i++; // increment i as we have already added the i+1 digit
foundConsecutive = true;
}
}
result.append(newNumber);
}
if (!foundConsecutive) // if no consecutive equal digits were found then return the result;
return result.toString();
else // recurse to check for more consecutive equal digits
return addConsecutiveDigits(result.toString());
}
I'm not a Java guy, so this code might not be ideal but I would do something like this:
public String solve(String input)
{
String result = "";
int i = 0;
while (i < input.length())
{
var first = input.charAt(i);
if (i == input.length() - 1){
result += first;
break;
}
var second = input.charAt(i + 1);
if (first == second){
result += (Character.getNumericValue(first) + Character.getNumericValue(second));
i += 2;
} else {
result += first;
i += 1;
}
}
return result;
}
For the second part, I would just run the function in a loop until the result matches the input.

Plus one leetcode

I am doing a question on leetcode, 66. Plus One.
You are given a large integer represented as integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
My solution is:
class Solution {
public int[] plusOne(int[] digits) {
int num = 0;
for (int a : digits) {
num = 10*num + a;
}
int n=num+1;
String str=String.valueOf(n);
int arr[]=new int[str.length()];
for(int i=0;i<str.length();i++){
arr[i]=str.charAt(i)-'0';
}
return arr;
}
}
I am getting many test cases failed, one being:
Input:
[9,8,7,6,5,4,3,2,1,0]
Output:
[1,2,8,6,6,0,8,6,1,9]
Expected:
[9,8,7,6,5,4,3,2,1,1]
Can anyone help me with it?
Think before you leap. And consider the edges.
Why would they do the seemingly idiotic move of storing an number, digit by digit, in an int array? Makes no sense, right?
Except... computers aren't magic. int can't represent any number. A computer's storage is not infinite. Specifically, an int covers 32 bits (4 bytes), and thus can only represent at most 2^32 different numbers. int 'uses' its alloted space of 2^32 by dividing it evenly amongst positive and negative numbers, but negative numbers get one more (because the '0' is in the positive space). In other words, all numbers from -2^31 to +2^31-1, inclusive.
9876543210 is larger than that.
You're trying to turn that array of digits into an int and that is a dead end. Once you do that, you get wrong answers and there is no fixing this. your algorithm is wrong. You can figure this stuff out, and you should always do that with leetcode-style problems, by first carefully reading the assignment. The assignment covers the limits. It says how large these arrays can be, and I'm sure it says that they can be quite large; large enough that the number inside it is larger than 2^31-1. Probably larger than 2^63-1 (which a long can reach).
Then you know the algorithm you need to write can't involve 'turn it into an int first'. That's usually the point (many problems are trivial if small, but become interesting once you make things large).
The algorithm they want you to write must not involve any conversion whatsoever. Increment the array in place. This isn't hard (just think about it: without converting anything, how do you turn [1, 2, 3] into [1, 2, 4]? That should be simple. Then think about how to deal with [1, 9, 9]. Finally, think about how to deal with [9, 9, 9]. Then you've covered all the cases and you have your answer.
In continuation to the detailed explanation of rzwitserloot, in case you are interested in code for the problem.
class Solution {
public int[] plusOne(int[] digits) {
int size = digits.length;
int i=0;
for(i = size-1 ; i >= 0 ; i--){
if (digits[i] != 9) {
digits[i] += 1;
break;
} else {
digits[i] = 0;
}
}
if(i == -1) {
int[] newDigits = new int[size+1];
newDigits[0] = 1;
return newDigits;
}
return digits;
}
}
This is a pretty trivial task, but in some test cases the value is too high to represent even as long, so the best candidate is BigInteger.
public int[] plusOne(int[] digits) {
BigInteger val = BigInteger.ZERO;
for (int i = 0; i < digits.length; i++)
val = val.multiply(BigInteger.TEN).add(BigInteger.valueOf(digits[i]));
val = val.add(BigInteger.ONE);
String str = val.toString();
digits = str.length() == digits.length ? digits : new int[str.length()];
for (int i = 0; i < digits.length; i++)
digits[i] = str.charAt(i) - '0';
return digits;
}
P.S. Sure, you can do this without BigInteger.
public int[] plusOne(int[] digits) {
boolean carry = true;
for (int i = digits.length - 1; carry && i >= 0; i--) {
carry = digits[i] == 9;
digits[i] = carry ? 0 : digits[i] + 1;
}
if (carry) {
int[] tmp = new int[digits.length + 1];
tmp[0] = 1;
System.arraycopy(digits, 0, tmp, 1, digits.length);
digits = tmp;
}
return digits;
}
Think about a mileage counter in a car. How does it work?
Whenever a 9 turns around, it turns the number left to it too.
So for incrementing by one, you'd start from the right, increment by one and if you incremented it to a 10, set it to a 0 instead and continue with the next digit to the left. If you reached the leftmost digit and still didnt finish, add a 1 to the left and set everything else to 0.
Example:
8
9 <- incremented rightmost
10 <- 9 turned to a 10, leftmost digit reached, add a 1 to the left and set everything else to 0
...
18
19 <- incremented rightmost
20 <- 9 turned to a 10, set to 0 instead, increment the next one to the left (1 -> 2), finished
...
108
109 <- incremented rightmost
110 <- 9 turned to a 10, set to 0 instead, increment the next one to the left (1 -> 2), finished
...
998
999 <- incremented rightmost
1000 <- 9 turned to a 10, set to 0 instead, increment the next one to the left, turned to a 10 too, set to 0 instead, ...
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class Scratch {
public static void main(String[] args) {
int[] digits = new int[0];
for (int i = 0; i < 100; i++) {
digits = plusOne(digits);
System.out.println(IntStream.of(digits).mapToObj(Integer::toString).collect(Collectors.joining()));
}
}
public static int[] plusOne(int[] digits) {
boolean finished = false;
for (int i = digits.length - 1; !finished && i >= 0; i--) {
if (++digits[i] % 10 == 0) {
digits[i] = 0;
} else {
finished = true;
}
}
if (!finished) {
// not finished after exiting the loop: every digit was turned from a 9 to a 10 -> we need one digit more
// initialize a new array with a length of 1 more digit, set the leftmost (index 0) to 1 (everything else is 0 by default)
digits = new int[digits.length + 1];
digits[0] = 1;
}
return digits;
}
}
plus one in leetcode solve on dart language
class Solution {
List<int> plusOne(List<int> digits) {
for(int i=digits.length - 1; i>=0; i--){
if(digits[i] < 9){
++digits[i];
return digits;
}
digits[i]=0;
}
List<int> ans = List.filled(digits.length+1, 0);
ans[0]=1;
return ans;
}
}
Here is my solution:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Plus One.
Memory Usage: 40.8 MB, less than 92.31% of Java online submissions for Plus One. for Plus One.
public int[] plusOne(int[] digits) {
for(int i=digits.length-1;i>=0;i--) {
if(digits[i]<9) {
digits[i]=digits[i]+1;
return digits;
}else {
digits[i]=0;
if(i==0) {
digits= new int[digits.length+1];
digits[0]=1;
}
}
}
return digits;
}
My solution:
Runtime: 0 ms, Memory Usage: 2.1 MB,
play.golang link: https://go.dev/play/p/Vm28BdaIi2x
// function to add one digit based on diff scenarios
func plusOne(digits []int) []int {
i := len(digits) - 1
// while the index is valid and the value at [i] ==
// 9 set it as 0 and move index to previous value
for i >= 0 && digits[i] == 9 {
digits[i] = 0
i--
}
if i < 0 {
//leveraging golang's simplicity with append internal method for array
return append([]int{1}, digits...)
} else {
digits[i]++
}
return digits
}

I'm trying to convert a binary number to a decimal number but my Output is always 0

Here is my code. I tried to Convert the binary to a Char array, then multiply each char in the array by 2 to the power of its corresponding number in the array, then sum up all the values of the char array into a double. New to programming so a bit confused. My input Binary is txfBinaryInput, and my output label is lblDisplay.
private void btnProcessActionPerformed(java.awt.event.ActionEvent evt)
{
if (txfBinaryInput.getText().equals(""))
{
lblDisplay.setText("ERROR: NO INPUT");
} else
{
int n = 0;
int[] binaryValueStorage = new int[100];
double[] decimalValueStorage = new double[100];
String binaryInput = txfBinaryInput.getText();
int binaryNumber = binaryInput.length();
char[] binaryDigits = binaryInput.toCharArray();
for (int i = 0; i >= binaryNumber; i++)
{
binaryValueStorage[n] = binaryDigits[n];
decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, n));
n++;
}
double sum = 0;
for (double a : decimalValueStorage)
{
sum += a;
}
lblDisplay.setText("The Deciaml Value Is " + sum);
}
}
Beware: in your for loop condition, you have i >= binaryNumber instead of i < binaryNumber, therefore your program will never enter the loop!
And on a side note, why are you using two variables, i and n, for the same purpose (incrementing and accessing the array)?
Edit: another issue:
In binary numbers, lower order bits are to the right, but in arrays, indices are from left to right!!
So you want your rightmost digit to be multiplied by 2^0, the next one right to its left by 2^1, and so on.
But in your code, what is happening is the opposite: it is the leftmost digit (your digit at index 0) that is being multiplied by 2^0!
To fix, you can either:
1) reverse your binaryDigits array before starting to convert, and keep the rest of your code untouched
2) replace decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, n)); by decimalValueStorage[n] = binaryValueStorage[n] * (Math.pow(2, binaryNumber - n));
Hope this helps!
Well, this is a lot to throw at you, but this is how I'd attack this problem:
public class BinaryToDecimalTest {
private static long binaryToDecimal(String binaryInput)
{
long sum = 0;
for (int i = 0 ; i < binaryInput.length() ; i++) {
sum *= 2;
if (binaryInput.charAt(i) == '1')
sum += 1;
}
return sum;
}
private static void test(String binaryInput) {
long n = binaryToDecimal(binaryInput);
System.out.println(String.format("The Deciaml Value of %s Is %d", binaryInput, n));
}
public static void main(String...args) {
test("0100");
test("1011");
test("1011");
test("10000000");
test("10000000000000000");
}
}
Result:
The Deciaml Value of 0100 Is 4
The Deciaml Value of 1011 Is 11
The Deciaml Value of 1010 Is 10
The Deciaml Value of 10000000 Is 128
The Deciaml Value of 10000000000000000 Is 65536
I don't want to just hit you with code, but I didn't know where to start given all of the issues with your code. I wanted you to see how directly you can often attack a problem. I'd be happy to keep working with you, and explain what's going on here.
The one dirty trick I'm using is multiplying the entire accumulated sum by two each time around. This lets you work naturally from the front of the array, rather than having to work your way backwards. The first digit gets multiplied by 2 (length - 1) times, the second (length - 2) times, etc., down to the last number, which doesn't get multiplied at all.

Magic Number - The Quest for the Simplest

Is there any better logic that can be applied to magic numbers?
Or is there a magic number that I am missing out on?
Please help me out with this simplest working code!
A Magic number is a number whose sum of digits eventually leads to 1.
Example#1: 19 ; 1+9 =10 ; 1+0 = 1. Hence a magic number.
Example#2: 226; 2+2+6=10; 1+0 =1. Hence a magic number.
Example#3: 874; 8+7+4=19; 1+9=10; 1+0=1. Hence a magic number.
boolean isMagic ( int n ) {
return n % 9 == 1;
}
Well, I'm not 100% that the code you placed would work to get a "magic number", but my approach to the problem would be different.
First, I'd receive a String, so that I can get the different digits of the number with a String.charat.
Then I'd use a while cycle to sum the numbers until it gets a single digit number, then check if it's 1.
The code would be
boolean isMagicNumber(String number) {
int[] digits = new int[number.length()];
int sum = 99;
while(sum/10 >= 1) {
sum = 0;
for(int i = 0; i < number.length(); i++) {
sum += Integer.parseInt(""+number.charAt(i));
}
if(sum == 1) {
return true;
}
}
return false;
}
There might be a better solution, but this is what I'd do to solve the problem.

Russian Doll Primes

This question was asked in an interview (about prime numbers)
Russian Doll Primes
They are more commonly known as Truncatable Primes.
I found this code on wiki
public static void main(String[] args){
final int MAX = 1000000;
//Sieve of Eratosthenes (using BitSet only for odd numbers)
BitSet primeList = new BitSet(MAX>>1);
primeList.set(0,primeList.size(),true);
int sqroot = (int) Math.sqrt(MAX);
primeList.clear(0);
for(int num = 3; num <= sqroot; num+=2)
{
if( primeList.get(num >> 1) )
{
int inc = num << 1;
for(int factor = num * num; factor < MAX; factor += inc)
{
//if( ((factor) & 1) == 1)
//{
primeList.clear(factor >> 1);
//}
}
}
}
//Find Largest Truncatable Prime. (so we start from 1000000 - 1
int rightTrunc = -1, leftTrunc = -1;
for(int prime = (MAX - 1) | 1; prime >= 3; prime -= 2)
{
if(primeList.get(prime>>1))
{
//Already found Right Truncatable Prime?
if(rightTrunc == -1)
{
int right = prime;
while(right > 0 && primeList.get(right >> 1)) right /= 10;
if(right == 0) rightTrunc = prime;
}
//Already found Left Truncatable Prime?
if(leftTrunc == -1 )
{
//Left Truncation
String left = Integer.toString(prime);
if(!left.contains("0"))
{
while( left.length() > 0 ){
int iLeft = Integer.parseInt(left);
if(!primeList.get( iLeft >> 1)) break;
left = left.substring(1);
}
if(left.length() == 0) leftTrunc = prime;
}
}
if(leftTrunc != -1 && rightTrunc != -1) //Found both? then Stop loop
{
break;
}
}
}
System.out.println("Left Truncatable : " + leftTrunc);
System.out.println("Right Truncatable : " + rightTrunc);
}
This gives the output:
Left Truncatable : 998443
Right Truncatable : 796339
But I am not able to solve this particular Russian doll prime number problem like if you have a prime number and you remove either left or right digit of this prime number then if that resulting number is prime number or not?
I am new to this so please pardon any mistake.
Let's start from the beginning:
According to the link you supplied with your question:
"Russian Doll Primes are
prime numbers whose right digit can be repeatedly removed, and are
still prime."
I will assume that you have a function boolean isPrime(int) to find out if a number is prime.
Googling, we will find from Wikipedia that the number of right-truncatable prime numbers up to 73,939,133 is 83, which makes brute-force a viable option; but a few optimization techniques can be employed here:
Since we right-truncate, we can safely eliminate even numbers (since any even number won't be prime, and so any number generated upon it will never be a russian doll prime).
Since any number that starts with 5 is divisible by 5, then based on the same rule I mentioned in the previous point, we can eliminate 5.
That leaves us with numbers that contain 1, 3, 7, and 9.
Now if we wanted to generate all possible combinations of these 4 numbers that do not exceed the maximum you mentioned (1,000,000), it would take only 4,096 iterations.
The downside of this technique is that we now have 4,096 numbers that contain possible non-prime numbers, or prime numbers that are formed from non-prime numbers and hence are not russian doll primes. We can eliminate these numbers by looping through them and checking; or better yet, we can examine russian doll primes more closely.
Upon examining the rule I quoted from your link above, we find that a russian doll primes are prime numbers whose right digit can be repeatedly removed, and are still prime (and hence are still russian doll prime, given the word repeatedly)!
That means we can work from the smallest single-digit russian doll primes, work our generation magic that we used above, and since any prime number that is formed from russian doll prime numbers is a russian doll prime number, we can eliminate non-primes early on, resulting in a clean list of russian doll prime numbers, while reducing the running time of such a program dramatically.
Take a look at the generation code below:
void russianDollPrimesGeneration(int x) {
x *= 10;
if (x * 10 >= 1000000) return;
int j;
for (int i=1; i<=9; i+=2) {
if (i == 5) continue;
j = x + i;
if (isPrime(j)) {
addToRussianDollPrimesList(j);
russianDollPrimesGeneration(j);
}
}
}
Provided that void addToRussianDollPrimesList(int x) is a function that adds x to a list that we previously preserved to store the russian doll prime numbers.
UPDATED NOTE
Note that you can put the call to void russianDollPrimesGeneration(int x) that we made inside the if condition inside the void addToRussianDollPrimesList(int x) function, because whenever we call the former function, we will always call the latter function with the same arguments. I'm separating them here to emphasize the recursive nature of the generation function.
Also note that you must run this function with the integer 0.
A final note is that there are a number of cases that the generation function void russianDollPrimesGeneration(int x) above won't count, even though they are Russian Doll Primes.
Remember when we omitted 2 and 5, because even numbers and numbers divided by 5 cannot be primes and so cannot be Russian Doll Primes? and consequently cannot form Russian Doll Primes? Well, that case does not apply to 2 and 5, because they are prime, and since they are single digits, therefore they are Russian Doll Primes, and are eligible to form Russian Doll Primes, if placed in the left-side, like 23 and 53.
So how to correct our code to include these special cases?
We can make a wrapper function that adds these two numbers and checks for Russian Doll Primes that can be formed using them (which will be the same generation function we are using above).
void generationWrapperFunction(int x) {
addToRussianDollPrimesList(2);
russianDollPrimesGeneration(2);
addToRussianDollPrimesList(5);
russianDollPrimesGeneration(5);
russianDollPrimesGeneration(0);
}
END UPDATED NOTE
This little function will produce a list of russian doll prime numbers, which can then be searched for the number we are looking for.
An alternative, yet I believe will be more time-consuming, is the following recursive function:
boolean isRussianDollPrime(int n) {
if (!isPrime(n)) return false;
if (n < 10) return true;
return isRussianDollPrime(n / 10);
}
This function can be modified to work with left-truncatable primes. The generation-based solution, however, will be much difficult to implement for left-truncatable primes.
Your problem is to use this code or to solve the problem ?
if to solve it you can generate primes using Sieve algorithm then check if the element is prime or not (if it was prime then check if element/10 is also prime)
Let's start with a simple assumption that we know how to write code to detect if a value is a prime. In a coding interview, they won't likely won't expect you to pull out "Sieve of Eratosthenes". You should start with simple code that handles the special cases of x<=1 (false) and x==2(true). Then check for an even number !(x % 2)(false). Then loop on i from 3..sqrt(x) (incrementing by +2 each time) to see if there's an odd number divisor for x.
boolean isPrime(long x)
{
// your code goes here
}
And once we have a function to tell us if a value is prime, we can easily build the function to detect if a value is a Russian Prime. Therefore we just need to loop on our value, each time check for prime, and then chop off the right hand side. And the easiest way to remove the right-most digit from a number is to simply divide it by 10.
boolean isRussianPrime(long x)
{
boolean result = isPrime(x);
while ((x != 0) && result)
{
// chop off the right digit of x
x = x / 10;
if (x != 0)
{
result = isPrime(x);
}
}
return result;
}
And that's really all there is to it.
package com.example.tests;
public class RussianDollPrimeNumber {
public static void main(String[] args) {
int x= 373;
int k;
int n =x;
for ( k= String.valueOf(x).length()-1;k>0;k--){
System.out.println(n);
if (isPrime(n)){
String m=String.valueOf(n).substring(0, k);
n=Integer.parseInt(m);
continue;
}else {
break;
}
}
if( k==0){
System.out.println("Number is Russianl Doll Number "+x);
}else {
System.out.println("Number is not Russianl Doll Number "+x);
}
}
private static boolean isPrime(int x) {
boolean check=true;
for (int i=2;i<x/2;i++){
if( (x%i)==0){
check=false;
}
}
return check;
}
}

Categories