Output Needed in Java - java

3! = 3*2*1 = 6
WITHOUT USING LOOP
Thank you!
My function below :
public static int factorial(int n)
{
if ((n == 1) || (n == 0))
return 1;
else
return(n * factorial(n-1));
}

You can print the value of the parameter passed in the factorial method like this:
create a function:
public static int factorial(int n) {
System.out.print(n); // here
if (n > 1) System.out.print("*"); // and here
if ((n == 1) || (n == 0))
return 1;
else {
return (n * factorial(n - 1));
}
}
Produces:
3!=3*2*1=6

You can use a global variable (StringBuffer) and append the numbers to it from the factorial method. Use this variable from main method when you print.

Related

guys any possible refractory code for the above code

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;
}

why there is no output in java even after using system.out.println function?

class PrimeTernary {
public static void main(String[] args) {
int i, m;
int n = 8;
m = n / 2;
String result;
if (n == 0 || n == 1)
System.out.println("Not prime number");
else
for (i = 3; i <= m; i++) {
result = (n % i == 0) ? "not prime" : "prime";
System.out.println(result);
}
}
}
what is wrong in my code? Can anyone pleased to explain it in brief?
Even if n is 0 or 1 (only then your print statement could ever be reached), then m is necessarily 0. This means, the for loop does not run.
Your if condition is never true since n is always 8.
if (n == 0 || n == 1) is the same as if (8 == 0 || 8 == 1)
So your loop will never execute.

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);
}
}

Computing integer powers with a recursive divide-and-conquer algorithm

I have implemented a recursive function to find m^n (m raised to the power n).
Now I want to implement the same function but by dividing the problem into two equal parts, like
m^n = m^(n/2) * m^(n/2) = ... (for even n like, m^2, m^4, m^6).
With the implementation below, if I give m = 2 and n = 4, my output is 4 while it should be 16.
public class Recursion {
public static void main(String[] args) {
System.out.println(pow(2, 4));
}
public static long pow(long m,long n) {
if (n > 0)
return m * pow(m, ((n/2) - 1) * pow(m, ((n/2) - 1)));
else
return 1;
}
}
public static long pow(long m,long n)
{
if (n <= 0) {
return 1; // Be lazy first
} else if (n % 2 == 1) {
return m * pow(m, n - 1); // Normal slow strategy
} else { // n even
long root = pow(m, n / 2); // Do not evaluate twice
return root * root;
}
}
Based on a combination of two other answers here, I believe this is the optimal algorithm:
public static long pow(long m, int n)
{
if (n <= 0) {
return 1;
} else if (n == 1) {
return m;
}
int rem = n & 1;
n >>= 1;
if (rem == 0) {
return pow(m * m, n); // x^(2n) = (x^2)^n
} else {
return m * pow(m * m, n); // x^(2n+1) = x * ((x^2)^n)
}
}
i.e. an immediate short-circuit for m^0 or m^1, and a single recursive call for other cases.
EDIT cleaned up slightly and now exactly follows the Wikipedia article on exponentiation by squaring which was algorithmically the same as my previous edit but is now improved by being the even-case being potentially tail recursive on languages that support it.
Try this, it computes by splitting into two parts as required. Also look at http://en.wikipedia.org/wiki/Exponentiation_by_squaring for other methods
class Main {
public static void main(String[] args) {
System.out.println(pow(2, 4));
}
public static long pow(long m, long n) {
if (n > 1)
return pow(m, (n / 2)) * pow(m, (n - (n / 2)));
else if (n <= 0)
return 1;
else
return m;
}
}
This answer adds error reporting on invalid inputs and handles all corner cases:
public long pow(long base, long exponent) {
if (exponent < 0) {
if (base == 1) {
return 1;
} else if (base == -1) {
return exponent % 2 == 0 ? 1 : -1;
} else {
throw new ArithmeticException("Negative exponent");
}
} else if (exponent == 0) {
if (base == 0) {
throw new ArithmeticException("0**0 is undefined");
} else {
return 1;
}
} else {
long root = pow(base, exponent/2);
long result = root * root;
if (exponent % 2 != 0) {
result *= base;
}
return result;
}
}
Technically this computes the result truncated to fit in a long. To detect overflow, the multiplications should be replaced with something like this.
For a non-recursive solution, replace the final else-block with
long result = 1;
while (exponent != 0) {
if (exponent % 2 != 0) {
result *= base;
}
base *= base;
exponent /= 2;
}
return result;
if you add up you ms you have
1+n/2-1+n/2-1
which reduces to
n - 1
Also, you have misplaced a few parenthesis, so you are not actually multiplying where you think you are. You are multiply the result of pow((n/2) -1) to the partialnin your firstpow` call.

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.

Categories