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.
Related
I've been trying to make a program that gives me a divisor of a number n that is closest to its square root.
I've tried to accomplish this by using this program:
public static int closestDivisor(int n) {
for (int i = n/ 2; i >= 2; i--) {
if (n % i == 0) {
return i;
}
}
return 1;
}
However, when I run this:
System.out.println(closestDivisor(42));
I get 21 when expecting either 6 or 7 because those are the closest divisors of 42.
if (i < 4) return 1;
int divisor = 1;
for (int i = 2; i < n; i++) {
if (i * i == n) return i;
if (i * i < n && n % i == 0) divisor = i;
if (i * i > n) return divisor;
}
return -1; // never executed, unreachable
This code should return the largest number which evenly divides n and which is less than or equal to the square root of n.
You can then look at this number, let's call it answer, and n/answer, and one of those is guaranteed to be the factor of n closest to the square root of n. To see which is which, we can compare n - answer*answer and (n/answer * n/answer) - n, and see which is smaller; if the first difference is smaller then answer is closer to n, otherwise n/answer is closer to n.
Here is one way.
First, return -1 if the candidate is < 0 or 1 if < 4
If n is a perfect square, return the square root.
Now inside the loop, Start from the square root and work outwards checking both sides of the square root for divisibility.
The default divisor is initialized to -1.
As the condition is evaluated either i divides n and i is returned via divisor
Otherwise k divides n and k is returned via divisor.
public static int closestDivisor(int n) {
if (n < 4) {
return n < 0 ? -1 : 1;
}
int v = (int)Math.sqrt(n);
int divisor = v;
if (v * v == n) {
return v;
}
for (int i = (int) v, k = i; i >= 1; i--, k++) {
if ( n % (divisor = i) == 0
|| (n % (divisor = k) == 0)) {
break;
}
}
return divisor;
}
public static int closestDivisor(int n) {
int closest = Integer.MAX_VALUE;
int closestDivisor = 1;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (Math.abs(i - n/i) < closest) {
closest = Math.abs(i - n/i);
closestDivisor = i;
}
}
}
return closestDivisor;
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;
}
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);
}
Can anybody help me programming the next problem (taken from Codingbat- Recursion1- count7)
Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
count7(717) → 2
count7(7) → 1
count7(123) → 0
There are some solutions which includes number of "returns".
I would like to program the problem with only 1 "return".
Well here's the solution I wrote and let's see how to do it with only one return
public int count7(int n)
{
int c = 0;
if (7 > n)
{
return 0;
}
else
{
if ( 7 == n % 10)
{
c = 1;
}
else
{
c = 0;
}
}
return c + count7(n / 10);
}
the same with only one return
public int count7(int n)
{
return (7 > n) ? 0 : ( ( 7 == n % 10) ? 1 + count7(n / 10) : 0 + count7(n / 10));
}
public int count7(int n) {
int counter = 0;
if( n % 10 == 7) counter++;
if( n / 10 == 0) return counter;
return counter + count7(n/10);
}
Sure PFB my solution in JAVA for the same
public int count7(int n) {
if((n / 10 == 0) && !(n % 10 == 7)) //First BASE CASE when the left most digit is 7 return 1
return 0;
else if((n / 10 == 0) && (n % 10 == 7)) //Second BASE CASE when the left most digit is 7 return 0
return 1;
else if((n % 10 == 7))
//if the number having 2 digits then test the rightmost digit and trigger recursion trimming it there
return 1 + count7(n / 10);
return count7(n / 10);
}
public int count7(int n) {
if(n == 0)
return 0;
else{
if(n%10 ==7)
return 1+count7(n/10);
return 0+count7(n/10);
}
}
public static int count7(int n){
if(n == 7)
return 1;
else if(n > 9){
int a = count7(n%10);
int b = count7(n/10);
return a + b;
}else
return 0;
}
public int count7(int n)
{
if(n==0)return 0;
if(n%10==7)return 1+count7(n/10);
else return count7(n/10);
}
public int count7(int n) {
if (n != 7 && n < 10) return 0;
else if (n == 7) return 1;
else if (n%10 == 7) return count7(n/10) + 1 ;
else return count7(n/10);
}
public int count7(int n){
if(n < 7)
return 0;
else if(n % 10 == 7)
return 1 + count7(n / 10);
else
return count7(n / 10);
}
the first if-statement is the base case that we would want to terminate on. The second checks to see if the rightmost digit is 7. If it is, chop the rightmost digit off and try again. When the recursive calls terminate and and values start getting returned up the chain, add 1 to include this successful check. In the case that neither of the above statements are true, chop off the rightmost digit and try again.
I know this is 2 years old, but hope this is a bit more readable and intuitive, and thus helpful.
Here is how I did it.
public int count7(int n) {
return (n==0?0:(count7(n/10)+(n%10==7?1:0)));
}
Recursion goes to 0 and it returns 0, when it comes back out checks if each number is 7, returns 1 if it is else 0. It continues adding those until all the way out.
Using one return will likely make it harder to read. If you are counting occurrences in recursion, an easy formula is to create a base case to terminate on, then provide an incremental return, and finally a return that will aid in reaching the base case without incrementing. For example..
public int count7(int n) {
if(n == 0) return 0;
if(n % 10 == 7) return 1 + count7(n / 10);
return count7(n / 10);
}
Using a one liner return like the one below in my opinion is harder to read or update because of the double ternary..
public int count7(int n)
{
return (n == 0) ? 0 : (n % 10 == 7) ? 1 + count7(n / 10) : count7(n / 10);
}
My solution works backwards from the nth digit to the first digit, by taking the modulus of the input. we add the number of sevens found into the return, for the final output.
Then checking whether the input is less than 7 can be the next step. If the input is less than 7 then there have never been any 7s in the input to begin with.
public int count7(int n) {
int sevens_found = 0;
if( n % 10 == 7 ) sevens_found ++;
return ( n < 7) ? 0 : ( n % 10 == 7 ) ? sevens_found + count7 ( n / 10 ) : count7 ( n / 10 );
}
#include<bits/stdc++.h>
using namespace std;
int count_occurences(int k){
int r;
if(k==0){
return 0;
}
r = k%10;
k = k/10;
if(r!=7){
return count_occurences(k);
}
return 1+count_occurences(k);
}
int main()
{
int x;
cin>>x;
cout<<" "<<count_occurences(x);
return 0;
}
public int count7(int n) {
int length = 0;
int counter = 0;
if ((n / 10) * 10 != n || (n / 10) != 0) {
if (n % 10 != 7) {
counter++;
}
length += 1 + count7(n / 10);
}
return length - counter;
}
The base case of n == 0 just "breaks" us out of the recursive loop, the n % 10 == 7 allows us to actually count the amount of 7s in an integer, and the return statement iterates through the given argument.
public int count7(int n) {
if (n == 0)
return 0;
if (n % 10 == 7)
return 1 + count7(n / 10);
return count7(n / 10);
}
public int count7(int n)
{
return occurrencesCounting(n, 0);
}
private int occurrencesCounting(int n, int count)
{
int counter = n % 10 == 7 ? count + 1 : count;
if (n / 10 == 0)
{
return counter;
}
return occurrencesCounting(n / 10, counter );
}
Here is what I have so far, and I am usually pretty good at tracing programs but i just can't figure out where i got stuck. It's supposed to get "N" and Mod it by D, which equals N-1, while D is greater than 1. And once it is done, it goes on the one number less than the original one, and does the same thing while N is greater than 2. And as for the "Count", i just added it so that I could check if the number was prime. Ex: if the count = N-2, which is basically every number from 2 to N-1, then that number is prime.
public class Challenge14 {
public void inti() {
int count = 0;
int N = 7;
int D = N - 1;
int A = 0;
while (N > 2) {
D = N - 1;
while (D > 1) {
A = N % D;
D--;
if (A == 0) {
break;
}
else {
count++;
}
}
if (count == N - 2) {
System.out.println(N);
}
N--;
}
}
}
Use a for loop.
for (int i = 1; i<N; i++) {
System.out.println(i);
}