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.
Related
I am only interested in n < 0 case, if n == -3 then I get, 0.001 as desired.
but I reached here through trial and error. Can someone explain to me 'WHY' this works (for n < 0 case only)?
public static double power10(int n) {
if(n == 0){
return 1;
}
else if (n > 10){
return 10 * power10(n - 1);
}
else {
return 1.0 / power10(-n);
}
}
The Following Function works for both negative and positive powers.
double Power(int n1,int n2) {
if(n2>=0) {
if(n2==1) {
return n1;
}
if(n2==0) {
return 1;
}
else {
return n1*Power(n1,n2-1);
}
}
else {
if(n2==-1) {
return 1.0/n1;
}
else {
return 1.0/(n1*Power(n1,(-1)*(n2+1)));
}
}
It will create following recursion tree for Negative example,
This link will redirect you to the recursion tree to better understanding, How this function will work recursively.
In fact, your code doesn't work for either 3 or -3. A stack overflow occurs in both cases. I don't know how you got 0.003.
The error in your code is this:
else if (n > 10){
It should be n > 0. instead.
This recursive algorithm should be quite clear if we turn it into a sentence starting with "the nth power of 10 is...":
The nth power of 10 is:
If n is 0, 1
If n is positive, 10 * (n-1)th power of 10
If n is negative, 1 / -nth power of 10
You can see that all values of n are covered, whether it be 0, positive or negative. In your incorrect code, you treat cases where 0 < n < 10 as "negative numbers". When you negate those and recurse, you get a real negative number, it goes into the else again and they are negated again. But they are still not larger than 10, causing infinite recursion.
Your code here probably give out stack overflow error.
Try
else if(n>0)
Now under the above condition function return n th value of 10 and return 1000 (when n is 3 case), Giving you the answer 0.001.
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.
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.
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.
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).