Recursion using modular arithmetic explain java - java

Could anyone explain how does this method works.
public static int calculate(int n){
if (n/10 == 0)
return n;
else
return (n % 10 + calculate(n/10));
}
I input n = 15 and it get a 6 but I don't understand how the method works. please help. thank you.

The method calculates the sum of the digits.
If the n is smaller than 10, you simply return n (since the sum of digits of a single digit number is the number itself).
Otherwise you add the least significant digit (that's n % 10) to the sum of digits of the number n / 10 (which is calculated recursively).

For n = 15 , here is how it works
15/10 > 0 , so the else condition is executed.
15%10 + calculate(15/10) i.e 5 + calculate(1).
The method is called again for n = 1;
Since 1/10 == 0 , 1 is returned
This 1 is then added to 5.
Therefore answer is 6.
So what this function does is return the sum of the digits that make up the number.

It goes like this:
calculate(15);
evaluates to
15%10 + calculate(1);
evaluates to
5 + 1;
which in the end; sums up to 6.
In other words; the above is an recursive approach to sum all the digits in a number. You could easily re-write this using a simple loop to avoid the recursion construct.

It cuts off the most right digit and moves on recursively with the rest of the number. (line 5)
If we have only one digit left (line 2), it is also added to the sum and the algorithm ends. (line 3)

In this example there is a if else condition so on the basis of input parameter there are 2 conditions '
-Firstly it checks in the if condition (n/10 == 0) .
-Consider your input as n=15.
now it checks if (n/10 == 0) i.e 15/10==0 which is false because 15/10=5 which is not equal to 0.
-As the condition is false it moves to else block where condition is to return
(n % 10 + calculate(n/10)
i.e. (15%10 +15/10)==5+1==6
-So the return is 6.

Related

How to solve program recursively

I need help with a program that satisfies the following quote:
All integers >= 2 can be factored into the product of only prime
numbers. For instance, the number 12 has a prime factorization of
2*2*3, while the number 100 has a prime factorization of 2*2*5*5. We
are interested in knowing whether an input integer has a prime
factorization that only has 2s and 3s.
I think I need more base conditions and a catch all recursive call.
Current (unfinished) Code:
public static boolean hasFactors2and3(int number) throws IllegalArgumentException{
if (number < 2) throw new IllegalArgumentException("Number is less than 2");
if (number >= 2 && number < 5) return true; // because for all these numbers it works
if (number % 2 == 0) return hasFactors2and3(number /= 2);
if (number % 3 == 0) return hasFactors2and3(number /= 3);
}
Any help is appreciated!
You ask for a recursive solution. I won't give you that. Instead I will give you a non-recursive solution in pseudocode and leave it up to you to convert it into a recursive solution.
function hasFactors2and3(number)
// Deal with negatives, 0, 1.
if (number < 2)
return false
endif
// Remove factors of 2.
while (number MOD 2 == 0)
number <- number / 2
endwhile
// Remove factors of 3.
while (number MOD 3 == 0)
number <- number / 3
endwhile
// See what factors are left after removing all 2s and 3s.
return number == 1
end function
Hint: research how to remove tail recursion by using a loop and then reverse the process.

Can someone explain me this recursive method?

This code counts the number 7 of your input. This is the code method:
public static int count7(int n) {
if (n == 0) {
return 0;
}
else if (n % 10 == 7) {
return 1 + count7 (n/10);
}
else {
return count7(n/10);
}
}
What does the else-if statement and else do? Thank you so much.
if (n == 0) {
return 0;
There are no 7s in 0, so return 0.
} else if (n % 10 == 7) {
checks if the least significant digit of the number is 7. If that's the case, the total number of 7s is 1 + the number of 7s in the number you get by removing that digit (by dividing the number by 10) :
return 1 + count7 (n/10);
} else {
If the least significant digit is not 7, the number of 7s is the number of 7s in n/10 :
return count7(n/10);
}
if (n % 10 == 7) if the remainder is 7 lets take example n=17 so 17%10 you are going to get 7 so add 1 means count that you have found 7 if you have not found then go to the else part and this time call by dividing it suppose this time n=28 clearly there is no 7 in this number so it will go to else if condition and it is going to be fail it will go to the else part and it will call the method by dividing n to 10 for the next iteration.
This is a recursive method.
The first if is the base case, i.e, if the numbers is 0, then it returns 0.
The else if checks if the digit is 7. If it is, then get the answer to the remaining digits (whether they have any 7s) using the same method, add 1 to it, and return the value.
The last else just removes one digit, and calls the method for the remaining digits.
This method counts the total amount of the digit 7 in a given number.
n % 10 == 7 inspects the least significant digit, and if it equals 7, then add 1 to the sum.
In any case, the algorithm goes on with the other digits by taking n / 10, which actually removes the least significant digit, and then calls the method recursively. As the number is decreasing with 1 digit with each call and the stop trigger n == 0 makes the method eventually stop, the final returned number counts the sevens in the initial number.
Example
count7(172) = 0 + count7(17) = 0 + 1 + count7(1) = 0 + 1 + 0 = 1
The function simply counts the total number of appearances of the digit 7 in any given non-negative integer.

Can a given number be written as a sum of two or more consecutive positive integers?

I need to write a method which takes in an int and returns true if the number can be written as a sum of two or more consecutive positive integers and false otherwise.
boolean IsSumOfConsecutiveInts(int num)
I figured out that all odd numbers (except the number 1) can be written as the sum of 2 consecutive positive integers:
return (num > 1 && num % 2 == 1);
but this doesn't account for numbers that can be written as the sum of more than 2 consecutive positive integers (such as 6 == 1 + 2 + 3).
How can I determine whether a number can be written as a sum of two or more consecutive positive integers?
These numbers are called Polite Numbers.
And, conveniently, the only numbers that aren't polite are the powers of 2.
So, that gives us 2 options. We can either determine that a number is polite, OR we can determine that it is not a power of 2.
I did both; the latter is easier (and more efficient).
This determines whether or not a number is polite:
boolean IsSumOfConsecutiveInts(int num)
{
int sumOfFirstIIntegers = 3;
for (int i = 2; sumOfFirstIIntegers <= num; i++)
{
if (i%2 == 0 ? (num%i == i/2) : (num%i == 0))
{
return true;
}
sumOfFirstIIntegers += i + 1;
}
return false;
}
This one is pretty hard to understand. It took me a while to come up with.
Basically, i is the number of consecutive integers that we are checking;
sumOfFirstIIntegers is equal to the sum of the first i integers, so that means that all the numbers that can be expressed as a sum of i consecutive integers are greater than or equal to sumOfFirstIIntegers.
The last part that deserves discussing is the boolean statement i%2 == 0 ? (num%i == i/2) : (num%i == 0). Let's look at some examples:
i all sums of i consecutive positive integers
2 3, 5, 7, 9...
3 6, 9, 12, 15...
4 10, 14, 18, 22...
5 15, 20, 25, 30...
There are two cases, but in either case, we can express all possible numbers that are a sum of i consecutive integers pretty simply.
When i is even, num must be equal to (i * n) + (i / 2) where n is a non-negative integer. This can of course be written as num % i == i / 2.
When i is odd, num must be equal to i * n, where n is a non-negative integer. Which gives us our second condition num % i == 0.
In addition to these conditions, num can not be less than the sum of the first i positive integers. Hence, our for loop's conditional: sumOfFirstIIntegers <= num.
This determines whether a number is not a power of 2:
boolean IsSumOfConsecutiveInts(int num)
{
return (num & (num - 1)) != 0;
}
This answer does a good job of explaining why this works.
Note that both of the above solutions have the same result, they are just different ways of thinking about the problem.

returning the first digit of an integer in an array

I have a method and I am interested in knowing how it actually works. I have searched the internet, but to no avail. This method when used returns the first digit of an entered integer in to an array.
What puzzles me is the divide AND operator. I know that the operator divides an operand on the left with the operator on the right and applies the answer to the left side.
Here is the method:
public static int firstDigit(int index)
{
while (index > 9)
index /= 10;
return (index);
}
In my program when an integer is entered, say 100 it reads out the number 1, as its the first number of the entered integer.
shouldn't this answer be 10, because index = 100 /= 10 = 10?
Sorry if im doing it wrong, i'm new here and at programming, i did a considerable amount of research before i asked this question.
shouldn't this answer be 10, because index = 100 /= 10 = 10?
No. 10 is more than 9, so it divides it again.
The key part here is the while loop. In the function above, it was written without brackets, but it could be rewritten as
public static int firstDigit(int index)
{
while (index > 9)
{
index /= 10;
}
return (index);
}
I'm not going to explain what a while loop is in detail, but it basically repeats the process while the condition is true.
So in the case of 100, it does this:
"Is index more than 9?" Yes. Set index to index/10. (Index now equals 10). "Is index more than 9?" Yes. Set index to index/10. (Index now equals 1). "Is index more than 9?" No. Return index. (1).
In the case of 99, it does this:
"Is index more than 9?" Yes. Set index to index/10. (Index now equals 9.9, round that to 9). "Is index more than 9?" No. Return index. (9).
Suppose the input is 100 :
You start with index = 100
then index = index / 10 = 10
since 10 > 9, you divide by 10 again :
index = index / 10 = 1
Then you exit the loop and return 1.
Basically, what this method does is compute index / 10^(n-1), where n is the number of digits. This gives you the most significant digit.
The line with while in it means that the following line (the one that does the division) happens repeatedly until the number that's left is less than ten. So 100 is divided by 10 to give 10, and then 10 is divided by 10 to give 1, which is returned.
shouldn't this answer be 10, because index = 100 /= 10 = 10?
No, it shouldn't. Why? Because of the while loop
while (index > 9)
in the first iteration, index enters in the loop as 100, and it is modified to 100/10 = 10.
Then, the condition index > 9 is evaluated. Since it's true (10 > 9) the program continues with the next iteration. Therefore, index is modified to 10/10 = 1.
The condition is evaluated again index > 9, but this time it's false (1 > 9), so the program exits the loop and returns the last value of index, 1.

Java program divisible by three without using modulus

I'd like to create a program wherein a user will type a number and the program will tell if it is divisible by 3 or not. But %, /, +, * can't be used in the program. Anybody here got some ideas how to do that?
public static void main(String[] args) {
String number = "123456";
int sum = 0;
for (char c : number.toCharArray()) {
sum = sum - (0 - c) - '0';
while (sum >= 3) {
sum -= 3;
}
}
System.out.print("divisible by 3? ");
System.out.println(sum == 0);
}
Alternatively you can keep subtracting 3 until your number is either 0 (divisible by 3) or <0: not divisible by 3.
ps: it needs to be adapted if you want to deal with negative numbers
easy peasy...
boolean divisibleBy3(int n) {
return (""+n).matches("([0369]|[147]([0369]|[147][0369]*[258])*([" +
"258]|[147][0369]*[147])|[258]([0369]|[258]" +
"[0369]*[147])*([147]|[258][0369]*[258]))*");
}
A number is divisible by there if the sum of all the digits is also divisible by 3. You can iterate the process until you have a number smaller than 10 and compare it which known divisors (3,6 and 9)
Since it is most likely a game or homework and you can use + you can simple use minus two times: a - - b is equivalent to a + b
Assuming you can use the - operator then
bool divBy3(int n)
{
while (n >= 0)
{
n -= 3;
}
return n == 0;
}
This will return true if n is exactly divisible by 3, false otherwise. Note that this is really inefficient! Using the % operator would be far better.
Divisibility by 3 in binary representation is like divisibility by 11 in decimal (10+1): sum of digits in even places minus sum of digits on odd places is in turn divisible by 3 (maybe 0).

Categories