I have a question how to better tackle this task, I have a version, but I am sure there is a better and shorter way to do this maybe. I need to take any int number(return it as an int without turning it into a String), but never with a 0 at the end (100, 120) but like 1234, or 4132. I need to take this number and using recursion rewrite it the other way around example 1234 to 4321, 4132 to 2314, maybe there is a way this is called, i personally don't know about it.
Here is what I got:
public static int reverse(int r, int n, int k){
if(r==0)
return 0;
else
return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1)
}
public static void main(String[] args) {
System.out.println(reverse(1234, 4, 0));
}
Working with a String representation of the int may make the code more readable.
Try:
Integer.parseInt(new StringBuilder(r+"").reverse().toString());
Current code doesn't compile. Added a ) to this line:
from if(r==0{ change to if(r==0){
and added a ; in this line return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1);
Your code after this two changes will look like:
public static int reverse(int r, int n, int k){
if(r==0)
{
return 0;
}else{
return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1);
}
}
if the number ends with 0, the program will not show any special message to the user, i.e 1230 will return 321. In this case, maybe
maybe print a message ("number must not end with a 0) or throw an exception?
Didn't notice the recursion part.
public static void main(String[] args) {
int i = 589;
System.out.println(reverse(i));
}
public static int reverse(int k){
if(k/10 == 0){return k;}
else return (k%10 * (int)Math.pow(10, (int)Math.log10(k))) + reverse(k /10);
}
Explanation:
k%10 gives you the last digit of an int
(int) (Math.log10(k)) returns
number of Digits in an Integer minus one
public static final int reverse(int number) {
final int lastDigit = number % 10;
final int length = (int) Math.log10(number);
return (number < 10) ? number : (int) (Math.pow(10.0, length) * lastDigit + reverse(number / 10));
}
If the number is lower then 10 it's the number itself. Otherwise it's the last digit multiplied with 10^n where n is the length of the number, so it's now at the position for the first digit.
Then add the result of a reverse of the rest number to it (the number without the last digit).
You take advance of the recursion function itself as it would already work to solve the big problem. You only have to think about the trivial end condition and one single step (which mostly is something you would suggest as the last step)
This is the best way that I could make it using recursion and without conversions.
private static int myReverse(int n, int r) {
if(n == 0)
return r;
int newR = r*10 + n%10;
return myReverse(n/10, newR);
}
What I'm doing here is:
Two parameters: n - the number you want to reverse, r - the reversed number
The recursion stops when n equals 0 because it always dividing it by 10
newR - This variable is unnecessary but it´s better for 'understanding' porposes, first I multiply r by 10 so I can sum the last value o n. For example, reverse 123: along the way if r = 12 and n = 3, first 12*10 = 120, n%10 = 3 then r*10 + n%10 = 123
A 'pleasant' way with only one return statement:
private static int myReverse2(int n, int r) {
return n == 0 ? r : myReverse2(n/10, r*10 + n%10);
}
Related
I was playing around with a few practice problems in Java. I wrote a recursive program for program given below. My solution is right except for the suspended (which I believe) gets back to active state and changes the value of the recursive method. I have also added a screenshot of Eclipse in debug mode where the thread stack is shown.
package com.nix.tryout.tests;
/**
* For given two numbers A and B such that 2 <= A <= B,
* Find most number of sqrt operations for a given number such that square root of result is a whole number and it is again square rooted until either the
* number is less than two or has decimals.
* example if A = 6000 and B = 7000, sqrt of 6061 = 81, sqrt of 81 = 9 and sqrt of 9 = 3. Hence, answer is 3
*
* #author nitinramachandran
*
*/
public class TestTwo {
public int solution(int A, int B) {
int count = 0;
for(int i = B; i > A ; --i) {
int tempCount = getSqrtCount(Double.valueOf(i), 0);
if(tempCount > count) {
count = tempCount;
}
}
return count;
}
// Recursively gets count of square roots where the number is whole
private int getSqrtCount(Double value, int count) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
++count;
getSqrtCount(sqrt, count);
}
return count;
}
public static void main(String[] args) {
TestTwo t2 = new TestTwo();
System.out.println(t2.solution(6550, 6570));
}
}
The above screenshot is from my debugger and I've circled the Thread stack. Can anyone try and run the program and let me know what the problem is and what would be the solution? I could come up with a non recursive solution.
Your recursion is wrong, since the value of count will return in any case 0 or 1 even if it goes deep down into recursive calls. Java is pass by value, meaning that modifying the value of a primitive inside of a method wont be visible outside of that method. In order to correct this, we can write the following recursion:
private int getSqrtCount(Double value) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
return getSqrtCount(sqrt) + 1;
}
return 0;
}
Your code is wrong, you should have
return getSqrtCount(sqrt, count);
instead of
getSqrtCount(sqrt, count);
Otherwise the recursion is pointless, you're completely ignoring the result of the recursion.
I have tried:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
This does not yield a value as I'm not sure how to do that.
public int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
static int power(int x, int y)
{
// Initialize result
int temp;
if( y == 0) // Base condition
return 1;
temp = power(x, y/2); // recursive calling
if (y%2 == 0) //checking whether y is even or not
return temp*temp;
else
return x*temp*temp;
}
Well others have written solution which gives you correct answer but their time complexity is O(n) as you are decreasing the power only by 1. Below solution will take less time O(log n). The trick here is that
x^y = x^(y/2) * x^(y/2)
so we only need to calculate x^(y/2) and then square it. Now if y is even then there is not problem but when y is odd we have to multiply it with x. For example
3^5 = 3^(5/2) * 3^(5/2)
but (5/2) = 2 so above equation will become 3^2 * 3^2, so we have to multiply it with 3 again then it will become 3 * 3^(5/2) * 3^(5/2)
then 3^2 will be calculated as 3^(2/1) * (3^2/1) here it no need to multiply it with 3.
public static double pow(int a, int pow) {
if (pow == 0)
return 1;
if (pow == 1)
return a;
if (pow == -1)
return 1. / a;
if (pow > 1)
return a * pow(a, pow - 1);
return 1. / (a * pow(a, -1 * (pow + 1)));
}
Considering X as number and n as power and if both are positive integers
public static int power(int n, int X) {
if (n == 0) {
return 1;
} else if(n == 1) {
return X;
} else {
return X * power(n-1, X);
}
}
Let's re-write your function:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
First of all, lets change void to int.
Afterthat, when n equals to 1, we return the result as X, because X^1 = X:
static public int power(int n, int X) {
if (n>1) {
return X * power(n-1, X);
}
return X;
}
Scanner s = new Scanner(System.in) ;
System.out.println("Enter n");
int n = s.nextInt();
System.out.println("Enter x");
int x =s.nextInt();
if (n>0){
double pow =Math.pow(n,x);
System.out.println(pow);
}
While others have given you solutions in terms of code, I would like to focus on why your code didn't work.
Recursion is a programming technique in which a method (function) calls itself. All recursions possess two certain characteristics:
When it calls itself, it does so to solve a smaller problem. In your example, to raise X to the power N, the method recursively calls itself with the arguments X and N-1, i.e. solves a smaller problem on each further step.
There's eventually a version of the problem which is trivial, such that the recursion can solve it without calling itself and return. This is called base case.
If you are familiar with mathematical induction, recursion is its programming equivalent.
Number two above is what your code is lacking. Your method never returns any number. In the case of raising a number to a power, the base case would be to solve the problem for the number 0 as raising zero to any power yields one, so the code does not need to call itself again to solve this.
So, as others have already suggested, you need two corrections to your code:
Add a return type for the method.
State the base case explicitly.
public class HelloWorld{
public long powerfun(int n,int power,long value){
if(power<1){
return value;
}
else{
value = value * n;
return powerfun(n,power-1,value);
}
}
public static void main(String []args){
HelloWorld hello = new HelloWorld();
System.out.println(hello.powerfun(5,4,1));
}
}
I've tried to add comments to explain the logic to you.
//Creating a new class
public class RecursivePower {
// Create the function that will calculate the power
// n is the number to be raised to a power
// x is the number by which we are raising n
// i.e. n^x
public static int power(int n, int x){
// Anything raised to the 0th power is 1
// So, check for that
if (x != 0){
// Recursively call the power function
return (n * power(n, x-1));
// If that is true...
}else{
return 1;
} //end if else
} //end power
// Example driver function to show your program is working
public static void main(String[] args){
System.out.println("The number 5 raised to 6 is " + power(5,6));
System.out.println("The number 10 raised to 3 is " + power(10,3));
} //end psvm
} //end RecursivePower
I have been trying this for some time now but could not get it to work. I am trying to have a method to reverse an integer without the use of strings or arrays. For example, 123 should reverse to 321 in integer form.
My first attempt:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
int tempRev = RevDigs(input/10);
if(tempRev >= 10)
reverse = input%10 * (int)Math.pow(tempRev/10, 2) + tempRev;
if(tempRev <10 && tempRev >0)
reverse = input%10*10 + tempRev;
if(tempRev == 0)
reverse = input%10;
return reverse;
}//======================
I also tried to use this, but it seems to mess up middle digits:
/** reverses digits of integer using recursion */
public int RevDigs(int input)
{
int reverse = 0;
if(input == 0)
{
return reverse;
}
if(RevDigs(input/10) == 0)
reverse = input % 10;
else
{
if(RevDigs(input/10) < 10)
reverse = (input % 10) *10 + RevDigs(input/10);
else
reverse = (input % 10)* 10 * (RevDigs(input/10)/10 + 1) + RevDigs(input/10);
}
return reverse;
}
I have tried looking at some examples on the site, however I could not get them to work properly. To further clarify, I cannot use a String, or array for this project, and must use recursion. Could someone please help me to fix the problem. Thank you.
How about using two methods
public static long reverse(long n) {
return reverse(n, 0);
}
private static long reverse(long n, long m) {
return n == 0 ? m : reverse(n / 10, m * 10 + n % 10);
}
public static void main(String... ignored) {
System.out.println(reverse(123456789));
}
prints
987654321
What about:
public int RevDigs(int input) {
if(input < 10) {
return input;
}
else {
return (input % 10) * (int) Math.pow(10, (int) Math.log10(input)) + RevDigs(input/10);
/* here we:
- take last digit of input
- multiply by an adequate power of ten
(to set this digit in a "right place" of result)
- add input without last digit, reversed
*/
}
}
This assumes input >= 0, of course.
The key to using recursion is to notice that the problem you're trying to solve contains a smaller instance of the same problem. Here, if you're trying to reverse the number 13579, you might notice that you can make it a smaller problem by reversing 3579 (the same problem but smaller), multiplying the result by 10, and adding 1 (the digit you took off). Or you could reverse the number 1357 (recursively), giving 7531, then add 9 * (some power of 10) to the result. The first tricky thing is that you have to know when to stop (when you have a 1-digit number). The second thing is that for this problem, you'll have to figure out how many digits the number is so that you can get the power of 10 right. You could use Math.log10, or you could use a loop where you start with 1 and multiply by 10 until it's greater than your number.
package Test;
public class Recursive {
int i=1;
int multiple=10;
int reqnum=0;
public int recur(int no){
int reminder, revno;
if (no/10==0) {reqnum=no;
System.out.println(" reqnum "+reqnum);
return reqnum;}
reminder=no%10;
//multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
i++;
no=recur(no/10);
reqnum=reqnum+(reminder*multiple);
multiple =multiple * 10;
System.out.println(i+" i multiple "+multiple+" Reminder "+reminder+" no "+no+" reqnum "+reqnum);
return reqnum;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int num=123456789;
Recursive r= new Recursive();
System.out.println(r.recur(num));
}
}
Try this:
import java.io.*;
public class ReversalOfNumber {
public static int sum =0;
public static void main(String args []) throws IOException
{
System.out.println("Enter a number to get Reverse & Press Enter Button");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
int number = Integer.parseInt(input);
int revNumber = reverse(number);
System.out.println("Reverse of "+number+" is: "+revNumber);
}
public static int reverse(int n)
{
int unit;
if (n>0)
{
unit = n % 10;
sum= (sum*10)+unit;
n=n/10;
reverse(n);
}
return sum;
}
}
This is the question I've been assigned:
A so-called “star number”, s, is a number defined by the formula:
s = 6n(n-1) + 1
where n is the index of the star number.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) star numbers are: 1, 13, 37,
73, 121, 181
In contrast a so-called “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) triangle numbers are: 1, 3, 6, 10, 15, 21
Write a Java application that produces a list of all the values of type int that are both star number and triangle numbers.
When solving this problem you MUST write and use at least one function (such as isTriangeNumber() or isStarNumber()
or determineTriangeNumber() or determineStarNumber()). Also you MUST only use the formulas provided here to solve the problem.
tl;dr: Need to output values that are both Star Numbers and Triangle Numbers.
Unfortunately, I can only get the result to output the value '1' in an endless loop, even though I am incrementing by 1 in the while loop.
public class TriangularStars {
public static void main(String[] args) {
int n=1;
int starNumber = starNumber(n);
int triangleNumber = triangleNumber(n);
while ((starNumber<Integer.MAX_VALUE)&&(n<=Integer.MAX_VALUE))
{
if ((starNumber==triangleNumber)&& (starNumber<Integer.MAX_VALUE))
{
System.out.println(starNumber);
}
n++;
}
}
public static int starNumber( int n)
{
int starNumber;
starNumber= (((6*n)*(n-1))+1);
return starNumber;
}
public static int triangleNumber( int n)
{
int triangleNumber;
triangleNumber =+ n;
return triangleNumber;
}
}
Here's a skeleton. Finish the rest yourself:
Questions to ask yourself:
How do I make a Triangle number?
How do I know if something is a Star number?
Why do I only need to proceed until triangle is negative? How can triangle ever be negative?
Good luck!
public class TriangularStars {
private static final double ERROR = 1e-7;
public static void main(String args[]) {
int triangle = 0;
for (int i = 0; triangle >= 0; i++) {
triangle = determineTriangleNumber(i, triangle);
if (isStarNumber(triangle)) {
System.out.println(triangle);
}
}
}
public static boolean isStarNumber(int possibleStar) {
double test = (possibleStar - 1) / 6.;
int reduce = (int) (test + ERROR);
if (Math.abs(test - reduce) > ERROR)
return false;
int sqrt = (int) (Math.sqrt(reduce) + ERROR);
return reduce == sqrt * (sqrt + 1);
}
public static int determineTriangleNumber(int i, int previous) {
return previous + i;
}
}
Output:
1
253
49141
9533161
1849384153
You need to add new calls to starNumber() and triangleNumber() inside the loop. You get the initial values but never re-call them with the updated n values.
As a first cut, I would put those calls immediatly following the n++, so
n++;
starNumber = starNumber(n);
triangleNumber = triangleNumber(n);
}
}
The question here is that "N" neednt be the same for both star and triangle numbers. So you can increase "n" when computing both star and triangle numbers, rather keep on increasing the triangle number as long as its less the current star number. Essentially you need to maintain two variable "n" and "m".
The first problem is that you only call the starNumber() method once, outside the loop. (And the same with triangleNumber().)
A secondary problem is that unless Integer.MAX_VALUE is a star number, your loop will run forever. The reason being that Java numerical operations overflow silently, so if your next star number would be bigger than Integer.MAX_VALUE, the result would just wrap around. You need to use longs to detect if a number is bigger than Integer.MAX_VALUE.
The third problem is that even if you put all the calls into the loop, it would only display star number/triangle number pairs that share the same n value. You need to have two indices in parallel, one for star number and another for triangle numbers and increment one or the other depending on which function returns the smaller number. So something along these lines:
while( starNumber and triangleNumber are both less than or equal to Integer.MAX_VALUE) {
while( starNumber < triangleNumber ) {
generate next starnumber;
}
while( triangleNumber < starNumber ) {
generate next triangle number;
}
if( starNumber == triangleNumber ) {
we've found a matching pair
}
}
And the fourth problem is that your triangleNumber() method is wrong, I wonder how it even compiles.
I think your methodology is flawed. You won't be able to directly make a method of isStarNumber(n) without, inside that method, testing every possible star number. I would take a slightly different approach: pre-computation.
first, find all the triangle numbers:
List<Integer> tris = new ArrayList<Integer>();
for(int i = 2, t = 1; t > 0; i++) { // loop ends after integer overflow
tris.add(t);
t += i; // compute the next triangle value
}
we can do the same for star numbers:
consider the following -
star(n) = 6*n*(n-1) + 1 = 6n^2 - 6n + 1
therefore, by extension
star(n + 1) = 6*(n+1)*n + 1 = 6n^2 + 6n +1
and, star(n + 1) - star(n - 1), with some algebra, is 12n
star(n+1) = star(n) + 12* n
This leads us to the following formula
List<Integer> stars = new ArrayList<Integer>();
for(int i = 1, s = 1; s > 0; i++) {
stars.add(s);
s += (12 * i);
}
The real question is... do we really need to search every number? The answer is no! We only need to search numbers that are actually one or the other. So we could easily use the numbers in the stars (18k of them) and find the ones of those that are also tris!
for(Integer star : stars) {
if(tris.contains(star))
System.out.println("Awesome! " + star + " is both star and tri!");
}
I hope this makes sense to you. For your own sake, don't blindly move these snippets into your code. Instead, learn why it does what it does, ask questions where you're not sure. (Hopefully this isn't due in two hours!)
And good luck with this assignment.
Here's something awesome that will return the first 4 but not the last one. I don't know why the last won't come out. Have fun with this :
class StarAndTri2 {
public static void main(String...args) {
final double q2 = Math.sqrt(2);
out(1);
int a = 1;
for(int i = 1; a > 0; i++) {
a += (12 * i);
if(x((int)(Math.sqrt(a)*q2))==a)out(a);
}
}
static int x(int q) { return (q*(q+1))/2; }
static void out(int i) {System.out.println("found: " + i);}
}
I just gave a coding interview on codility
I was asked the to implement the following, but i was not able to finish it in 20 minutes, now I am here to get ideas form this community
Write a function public int whole_cubes_count ( int A,int B ) where it should return whole cubes within the range
For example if A=8 and B=65, all the possible cubes in the range are 2^3 =8 , 3^3 =27 and 4^3=64, so the function should return count 3
I was not able to figure out how to identify a number as whole cube. How do I solve this problem?
A and B can have range from [-20000 to 20000]
This is what I tried
import java.util.Scanner;
class Solution1 {
public int whole_cubes_count ( int A,int B ) {
int count =0;
while(A<=B)
{
double v = Math.pow(A, 1 / 3); // << What goes here?
System.out.println(v);
if (v<=B)
{
count=count+1;
}
A =A +1;
}
return count ;
}
public static void main(String[] args)
{
System.out.println("Enter 1st Number");
Scanner scan = new Scanner(System.in);
int s1 = scan.nextInt();
System.out.println("Enter 2nd Number");
//Scanner scan = new Scanner(System.in);
int s2 = scan.nextInt();
Solution1 n = new Solution1();
System.out.println(n.whole_cubes_count (s1,s2));
}
}
Down and dirty, that's what I say.
If you only have 20 minutes, then they shouldn't expect super-optimized code. So don't even try. Play to the constraints of the system which say only +20,000 to -20,000 as the range. You know the cube values have to be within 27, since 27 * 27 * 27 = 19683.
public int whole_cubes_count(int a, int b) {
int count = 0;
int cube;
for (int x = -27; x <= 27; x++) {
cube = x * x * x;
if ((cube >= a) && (cube <= b))
count++;
}
return count;
}
For the positive cubes:
i = 1
while i^3 < max
++i
Similarly for the negative cubes but with an absolute value in the comparison.
To make this more general, you need to find the value of i where i^3 >= min, in the case that both min and max are positive. A similar solution works if both min and max are negative.
Well, it can be computed with O(1) complexity, we will need to find the largest cube that fits into the range, and the smallest one. All those that are between will obviously also be inside.
def n_cubes(A, B):
a_cr = int(math.ceil(cube_root(A)))
b_cr = int(math.floor(cube_root(B)))
if b_cr >= a_cr:
return b_cr - a_cr + 1
return 0
just make sure your cube_root returns integers for actual cubes. Complete solution as gist https://gist.github.com/tymofij/9035744
int countNoOfCubes(int a, int b) {
int count = 0;
for (int startsCube = (int) Math.ceil(Math.cbrt(a)); Math.pow(
startsCube, 3.0) <= b; startsCube++) {
count++;
}
return count;
}
The solution suggested by #Tim is faster than the one provided by #Erick, especially when A...B range increased.
Let me quote the ground from github here:
"one can notice that x³ > y³ for any x > y. (that is called monotonic function)
therefore for any x that lies in ∛A ≤ x ≤ ∛B, cube would fit: A ≤ x³ ≤ B
So to get number of cubes which lie within A..B, you can simply count number of integers between ∛A and ∛B. And number of integers between two numbers is their difference."
It seems perfectly correct, isn't it? It works for any power, not only for cube.
Here is my port of cube_root method for java:
/*
* make sure your cube_root returns integers for actual cubes
*/
static double cubeRoot(int x) {
//negative number cannot be raised to a fractional power
double res = Math.copySign(Math.pow(Math.abs(x), (1.0d/3)) , x);
long rounded_res = symmetricRound(res);
if (rounded_res * rounded_res * rounded_res == x)
return rounded_res;
else
return res;
}
private static long symmetricRound( double d ) {
return d < 0 ? - Math.round( -d ) : Math.round( d );
}
I am aware of Math.cbrt in java but with Math.pow approach it is easy to generalize the solution for other exponents.