guys any possible refractory code for the above code - java

Guys I want to modify this if or block so dynamically it divide the value x based on what or condition got executed.
public boolean isUgly(int n) {
boolean isUgly=true;
while(n>0)
{
if(n%2==0||n%3==0||n%5==0)
{
n = n/x //<-------- here i want x should be based on the if condition where or is true
}
else {
isUgly=false;
break;
}
}
return isUgly;
}

You looking for something like this?
public static boolean isUgly(int n) {
final int[] uglyPrimes = {2, 3, 5};
boolean isUgly = true;
while (n > 1 && isUgly) {
isUgly = false;
for (int x : uglyPrimes) {
if (n % x == 0) {
n = n / x;
isUgly = true;
}
}
}
return isUgly;
}
Of course, I would just implement it like this:
public static boolean isUgly(int n) {
while (n > 1 && n % 2 == 0)
n /= 2;
while (n > 1 && n % 3 == 0)
n /= 3;
while (n > 1 && n % 5 == 0)
n /= 5;
return (n <= 1);
}
Or this:
public static boolean isUgly(int n) {
for (int x : new int[] { 2, 3, 5 })
while (n > 1 && n % x == 0)
n /= x;
return (n <= 1);
}
All 3 solutions really should have the following added to the beginning of the method, but that's outside the scope of the challenge:
if (n <= 0)
throw new IllegalArgumentException("Invalid value: " + n);

Try the following code, in this way you can divide n depending on the condition, but this method will always return false as in any case, it will execute the else statement for sure. What is your goal?
public boolean isUgly(int n)
{
boolean isUgly=true;
while(n>0)
{
if(n%2==0)
{
n = n/2;
}
else if(n%3==0)
{
n = n/3;
}
else if(n%5==0)
{
n = n/5;
}
else
{
isUgly=false;
break;
}
}
return isUgly;
}

Related

Finding Whether Two Numbers Share a Digit

I am working on this problem where I am supposed to use loops to find whether two numbers share a digit. The code I wrote does not return true if the shared digit is the first digit of a number. I can not find the bug in my code or any other solution. Please help!
public static boolean hasSharedDigit(int firstNumber, int secondNumber) {
if ((firstNumber < 10 || firstNumber > 99) || (secondNumber < 10 || secondNumber > 99)) {
return false;
}
int testFirstNumber = firstNumber;
int testSecondNumber = secondNumber;
while (testFirstNumber != 0) {
while (testSecondNumber != 0) {
if ((testFirstNumber % 10) == (testSecondNumber % 10)) {
return true;
}
testSecondNumber /= 10;
}
testFirstNumber /= 10;
}
return false;
}
You should reset testSecondNumber before the next testFirstNummber loop.
In your code, the inner loop is called only once, because testSecondNumber goes to 0 and is not reset.
The right solution is:
public static boolean hasSharedDigit(int firstNumber, int secondNumber) {
if ((firstNumber < 10 || firstNumber > 99) || (secondNumber < 10 || secondNumber > 99)) {
return false;
}
int testFirstNumber = firstNumber;
while (testFirstNumber != 0) {
int testSecondNumber = secondNumber;
while (testSecondNumber != 0) {
if ((testFirstNumber % 10) == (testSecondNumber % 10)) {
return true;
}
testSecondNumber /= 10;
}
testFirstNumber /= 10;
}
return false;
}
It seems that offered solution checks only 2-digit numbers so the performance is not the issue in this case and using nested loop should not have any serious impact.
However, if a common digit needs to be found for any integer numbers (not only positive), it would be better to use a small array to count digits in the first number and then verify if a digit from the 2nd number is present in this array without using nested loops.
static boolean commonDigits(int xx, int yy) {
// handle negative values
int x = Math.abs(xx);
int y = Math.abs(yy);
int[] digits = new int[10];
if (x == 0) { // handle 0
digits[0]++;
}
while (x > 0) {
digits[x % 10]++;
x /= 10;
}
// check for 0
if (y == 0 && digits[0] > 0) {
return true;
}
while (y > 0) {
if (digits[y % 10] > 0) {
return true;
}
y /= 10;
}
return false;
}
A shorter version based on converting a number into stream of characters via conversion to String may look like this:
static boolean commonDigitsStream(int x, int y) {
int[] digits = new int[10];
Integer.toString(Math.abs(x))
.chars()
.map(i -> i - '0')
.forEach(i -> digits[i]++);
return Integer.toString(Math.abs(y))
.chars()
.map(i -> i - '0')
.anyMatch(i -> digits[i] > 0);
}

How to encode a number using its prime factors in java using arrays?

I have this question I am trying to solve
I wrote this code
public static int[] encodeNumber(int n) {
int count = 0, base = n, mul = 1;
for (int i = 2; i < n; i++) {
if(n % i == 0 && isPrime(i)) {
mul *= i;
count++;
if(mul == n) {
break;
}
n /= i;
}
}
System.out.println("count is " + count);
int[] x = new int[count];
int j = 0;
for (int i = 2; i < base; i++) {
if(n % i == 0 && isPrime(i)) {
mul *= i;
x[j] = i;
j++;
if(mul == n) break;
n /= i;
}
break;
}
return x;
}
public static boolean isPrime(int n) {
if(n < 2) return false;
for (int i = 2; i < n; i++) {
if(n % i == 0) return false;
}
return true;
}
I am trying to get the number of its prime factors in a count variable and create an array with the count and then populate the array with its prime factors in the second loop.
count is 3
[2, 0, 0]
with an input of 6936. The desired output is an array containing all its prime factors {2, 2, 2, 3, 17, 17}.
Your count is wrong, because you count multiple factors like 2 and 17 of 6936 only once.
I would recommend doing it similar to the following way, recursively:
(this code is untested)
void encodeNumberRecursive(int remainder, int factor, int currentIndex, Vector<Integer> results) {
if(remainder<2) {
return;
}
if(remainder % factor == 0) {
results.push(factor);
remainder /= factor;
currentIndex += 1;
encodeNumberRecursive(remainder , factor, currentIndex, results);
} else {
do {
factor += 1;
} while(factor<remainder && !isPrime(factor));
if(factor<=remainder) {
encodeNumberRecursive(remainder , factor, currentIndex, results);
}
}
}
Finally, call it with
Vector<Integer> results = new Vector<Integer>();
encodeNumberRecursive(n, 2, 0, results);
You can also do it without recursion, I just feel it is easier.
Well here is a piece of code I would start with. It is not finished yet and I did not test it, but that's the way you should go basically.
// First find the number of prime factors
int factorsCount = 0;
int originalN = n;
while (n > 1) {
int p = findLowestPrimeFactor(n);
n /= p;
factorsCount++;
}
// Now create the Array of the appropriate size
int[] factors = new int[factorsCount];
// Finally do the iteration from the first step again, but now filling the array.
n = originalN;
int k = 0;
while (n > 1) {
int p = findLowestPrimeFactor(n);
factors[k] = p;
k++;
n = n / p;
}
return factors;
Having found a factor (on increasing candidates), you can assume it is prime,
if you divide out the factor till the candidate no longer is a factor.
Your problem is not repeatedly dividing by the factor.
public static int[] encodeNumber(int n) {
if (n <= 1) {
return null;
}
List<Integer> factors = new ArrayList<>();
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) { // i is automatically prime, as lower primes done.
factors.add(i);
n /= i;
}
}
return factors.stream().mapToInt(Integer::intValue).toArray();
}
Without data structures, taking twice the time:
public static int[] encodeNumber(int n) {
if (n <= 1) {
return null;
}
// Count factors, not storing them:
int factorCount = 0;
int originalN = n;
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) {
++factorCount;
n /= i;
}
}
// Fill factors:
n = originalN;
int[] factors = new int[factorCount];
factorCount = 0;
for (int i = 2; n != 1; i += 1 + (i&1)) {
while (n % i == 0) {
factors[factorCount++] = i;
n /= i;
}
}
return factors;
}

Java recursion exponentiation method making recursion more efficient

I'd like to change this exponentiation method (n is the exponent):
public static double exponentiate(double x, int n) {
counter++;
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
return x * exponentiate(x, n - 1);
}
}
I'd like to change the method to make it more efficient, so the method is not opened n times but maximum (n/2+1) times WITHOUT using the class MATH.
So far I came up with this code:
public static double exponentiate(double x, int n) {
counter++;
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
if (n % 2 == 0) {
n = n-(n-1);
} else {
n = ((n-1) / 2) + n;
}
return ((x * x) * exponentiate(x, n - (n / 2)));
}
}
But somehow it only works for odd n, not vor even n.
Can somebody help?
Thanks!
I think you can optimize the above method to run for O(logn) by calculating exponentiate(x,n/2) once and using it.
Something like this:-
public static double exponentiate(double x, int n)
{
int temp;
if(n == 0)
return 1;
temp = exponentiate(x, n/2);
if (n%2 == 0)
return temp*temp;
else
return x*temp*temp;
}
Hope this helps!
I don't know if this is the solution you search but this is an example of an algorithm that perform exponentiation in O(log(n)) time
public static double exponentiate(double x, int n) {
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
return ((n % 2 == 0) ? 1 : x) * exponentiate(x * x, n / 2);
}
}

finding the sum of number dividsable by x using recursion

I want to find the sum of numbers that is divisible by x using recursive method
Ex if n= 10, x=3, the code should return sum of 3+6+9
Write a recursive method sumDivByX(n, x), which finds the sum of all
numbers from 0 to n that are divisible by x.
I asked my teacher about it and he told me "Firstly, total should be global. You should return 0 if n or x == 0. I only care if n is divisible by x. So I only add n to total (total+=n) if (n%x==0) otherwise do nothing. And do recursion sumDivByX(n-1,x) and return total as usual." I tried to correct it.
public static int sumDivByX(int n, int x) {
int total = 0;
if (n == 0 || x == 0) {
return -1;
}
if (n % x >= 1) {
return total = 0;
} else if (n % x == 0) {
return total += n;
}
return total + sumDivByX(n - 1, x);
}
When I run the program I get 0.
Eliminate the returns inside your second and third if statements
public static int sumDivByX(int n, int x) {
int total = 0;
if (n == 0 || x == 0) {
return 0;
}
if (n % x >= 1) {
total = 0;
} else if (n % x == 0) {
total += n;
}
return total + sumDivByX(n - 1, x);
}
For a cuter, more compact version
public static int sumDivByX(int n, int x) {
if (n == 0 || x == 0) {
return 0;
}
return (n % x == 0 ? n : 0) + sumDivByX(n - 1, x);
}
Note - depending on the semantics you intend, you might want to have separate checks for x<=0 (possibly and error?) and n==0 (base case).
Step through your code and you'll see that it never recurses when n ==10 and x==3, since (10 % 3 == 1)
When a method gets to a "return" statement it ends, in your case at the second if.
Your total is initialized by 0 everytime the method runs, so you should consider making it global.
Your method generates an exception if you try to use negative numbers as paramethers
Try this:
int total=0;
public static int subDivByX(int n, int X) {
if (n>0 && x>0) {
if (n%x==0){
total += n;
}
return sumDivByX(n-1,x);
}
else return -1;
}
This seems to work
private static int sumDivByX(int n,int x) {
if (n < x || x < 1 ) {
return 0;
}
int d = n/x;
return (x * d) + sumDivByX(n - x , x);
}
Recursion could cause a stackoverflow.

heavy prime number in java

A prime heavy number is defined to be one that is the sum of more than one pair of prime numbers. Recall that a prime number is a number greater than 1 whose only divisors are 1 and itself.
For example, 16 is prime heavy because 16=3+13 and 5+11 (note that 3, 5, 11, and 13 are all prime). 24 is prime heavy because 24 = 5+19, 7+17 and 11+13. However, 8 is not prime heavy because 8 = 3+5 but no other pair of primes sums to 8.
Write a function named isPrimeHeavy that returns 1 if its argument is prime heavy, otherwise it returns 0.
The function signature is
int isPrimeHeavy (int n)
You may assume that a function named isPrime already exists that returns 1 if its argument is a prime. You can call this function but do not have to write it.
I did this but it cant return a heavy prime..just returns a prime number...
public class Prime {
public static boolean isPrimeHeavy(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrimeHeavy(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
public class PrimeTest {
public PrimeTest() {
}
#Test
public void testIsPrime() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Prime prime = new Prime();
TreeMap<Long, String> methodMap = new TreeMap<Long, String>();
for (Method method : Prime.class.getDeclaredMethods()) {
long startTime = System.currentTimeMillis();
int primeCount = 0;
for (int i = 0; i < 1000000; i++) {
if ((Boolean) method.invoke(prime, i)) {
primeCount++;
}
}
long endTime = System.currentTimeMillis();
Assert.assertEquals(method.getName() + " failed ", 78498, primeCount);
methodMap.put(endTime - startTime, method.getName());
}
for (Entry<Long, String> entry : methodMap.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey() + " Milli seconds ");
}
}
}
You can use a single loop to try all the possible first values and you can calculate the second, when you find there is more than one pair, return 1, otherwise return 0.
I have given you this much as a hint because its maths really rather than programming. You will find problems like this at Project Euler. IMHO You shouldn't be expected to know how to solve the maths problem unless you are employed for a maths role, but you should be able to write the code if you are a professional developer.
if((argument % 2 == 0 && argument > 12) || argument == 10) {
return 1;
} else {
return 0;
}
public class Prime {
public static boolean isPrimeHeavy(int n) {
if (n % 2 != 0) {
return false;
}
int found = 0;
for (int i = n-3; i >= (n/2); i -= 2) {
if (isPrime(i) && isPrime(n - i)) {
found++;
if (found == 2)
return true;
}
}
return false;
}
}

Categories