I have to find sum of the all even numbers that are not divisible by 7 using recursion. I tried this code but it seems I am making mistake somewhere because it returns 0:
public static void main(String[] args) {
System.out.println(specialSum(50));
}
public static int specialSum(int a) {
if ((a >= 1) && ((specialSum(a-1))%7 !=0)) {
return a + specialSum(a -1);
} else{
return 0;
}
}
}
Instead of if ((a >= 1) && ((specialSum(a-1))%7 !=0)) try if ((a >= 1) && (a%7) !=0)), as it is now, you're never checking if the original a value is not divisible by 7, your first check is always a - 1.
In recursion, you just need to focus on current step, you shouldn't user specialSum(a -1) in a condition. This is the next step, you should only call it after focusing on the current step.
You should just apply your two rules to succeed : add the current number to the nexts only
- if they are even
- if they are not divisible by 7.
public static int specialSum(int a) {
if(a <= 1) // Final Case.
{
System.out.print(" 0 = ");
return 0;
}
if(a%2 != 0) // Even Number, do not sum, call next step
{
return specialSum(a-1);
}
else
{
if(a % 7 == 0){ // Divisible by 7 Do not sum, call next step.
return specialSum(a-1);
}
else // NOT divisible by 7 nor by 2, add it to the next step
{
System.out.print(a+ " + ");
return a + specialSum(a-1);
}
}
}
outputs :
50 + 48 + 46 + 44 + 40 + 38 + 36 + 34 + 32 + 30 + 26 + 24 + 22 + 20 + 18 + 16 + 12 + 10 + 8 + 6 + 4 + 2 + 0 = 566
Here you have the solution in one line, you should have a case to stop the recursion, in your case you stop the recursion at 49 because it is divisible by 7, and you don't take into account numbers less than 49
main()
{
specialSum(50, 7);
}
public static int specialSum(int a, int toDivide)
{
return (a == 0) ? 0 : (a >= 1 && a%2 == 0 && a%7 != 0) ? a + specialSum(a - 1, toDivide) : specialSum(a - 1, toDivide);
}
This works for me. The first if makes sure to only take even numbers. Then second if makes sure only to sum if not divisible by 7. The last if sums the result.
public static void main(String[] args) {
System.out.println(specialSum(50, 0));
}
public static int specialSum(int max, int current){
if(max % 2 == 1)
max -= 1;
if(max % 7 != 0)
current += max;
if(max >= 1){
max -= 2;
return specialSum(max, current);
}
return current;
}
This returns 566.
Equal to: 50 + 48 + 46 + 44 + 40 + 38 + 36 + 34 + 32 + 30 + 26 + 24 + 22 + 20 + 18 + 16 + 12 + 10 + 8 + 6 + 4 + 2.
public static int specialSum(int a) {
if ( a % 7 !=0 && a%2==0 ) {
return a + specialSum(a - 2);
} else {
if (a > 2 ) {
a=a-2;
return a + specialSum(a - 2);
} else {
return 0;
}
}
}
Your code is wrong.
The condition (specialSum(a-1))%7 !=0) in your code calls the method for 49, when a=50. This calls the method for 48, which calls for 47 and so on until a=1. Then, it calls for 0, which is not greater than or equal to 1, and hence it returns 0. Now, 0%n for any number, is 0. Hence, you get 0 as the output.
Change your method to something like this:
public static int specialSum(int a) {
if(a<=2) return 2; // base case
else if(a%7==0) return specialSum(a-2); // if it is divisible by 7, then do not add it, and call the method for a-2.
else return a+specialSum(a-2); // else add the number, and get the answer for a-2.
}
You need to check if a is divisible by 7, so you should use if ((a>=1) && (a%7) !=0)) to make sure that the you check for the base condition.
Related
I wrote a program where function isHappy takes in a long value and returns a statement of either True or False based on what the output number is... (1 means True; 4 means false).
The way my program reaches the output is by squaring each digit of the input n and adding them repeatedly until the output is only 1 digit
For instance, if n = 19, the code would return 1 because:
1^2 + 9^2 = 82, from which digits 8 and 2 would do: 8^2 + 2^2 = 68, from which digits 6^2 + 8^2 = 100, from which 1^2 + 0^2 + 0^2 = 1. <== 1 is only one digit, therefore, it shall be the answer.
Please note that every input I get will end up with either 1 or 4
Anyways, here is my code so far,
public class Happy
{
public static void main(String args[])
{
System.out.println(isHappy(989));
}
public static boolean isHappy(long n) {
long sum = 0;
boolean l = true;
boolean j = false;
while (n != 0) {
sum = sum + ((n % 10) * (n % 10));
n = n / 10;
}
if (sum == 1) {
return l;
} else {
return j;
}
}
}
When my plug in test case inputs like isHappy(100), isHappy(111), isHappy(1234), the program seems to work where
1 = True, 4 means false
isHappy(100) == true
isHappy(111) == false
isHappy(1234) == false
However, when I plug in specific numbers like isHappy(989), the program should be true since
9^2 + 8^2 + 9^2 = 226; 2^2 + 2^2 + 6^2 = 44; 4^2 + 4^2 = 32; 3^2 + 2^2 = 13; 1^2 + 3^2 = 10 and lastly 1^2 + 0^2 = 1; which is True.
However, after running my code, my output prints false instead.
I've tried debugging my code but I can't seem to find a problem. Any help on what changes to my code do I have to make would be greatly appreciated :)
You're mixing the two parts of the algorithm: calculating the sum of squared digits and verifying if the number is a "happy number".
After calculating the sum for the given number in case when the sum is naughtier 1, no 4, the sum becomes a new number to check, and we need to continue with calculating its sum.
So basically we need two loops, or two separate methods.
That that's how it can be implemented.
public static boolean isHappy(long n) {
while (n != 1 && n != 4) { // given number is naughtier `1`, no `4`
n = getHappySum(n); // calculating the sum
}
return n == 1;
}
public static int getHappySum(long n) {
int sum = 0;
while (n != 0) {
sum += Math.pow(n % 10, 2);
n /= 10;
}
return sum;
}
main()
public static void main(String[] args) {
System.out.println(isHappy(100));
System.out.println(isHappy(111));
System.out.println(isHappy(1234));
}
Output:
true
false
false
Returns a string consisting of a Hailstone sequence beginning with the positive integer n and ending with 1. The
string should consist of a sequence of numerals, with each numeral followed by a single space. When a numeral m
(other than 1) appears in the sequence, it should be followed by nextHailstone(m).
Examples: nextHailstone(1) is "1 " and nextHailstone(5) is "5 16 8 4 2 1 ".
public static String hailstones (int n)
{
int calculation = 1;
System.out.print(n + " ");
while (n > 1)
{
if (n % 2 == 0)
{
n /= 2;
}
else
{
n = (n*3) + 1;
}
calculation++;
System.out.print(n + " ");
}
return " ";
}
The code works fine when I call the method in the main method but the test case for it is failing.
#Test
public void testHailstones ()
{
assertEquals("1 ", hailstones(1));
assertEquals("16 8 4 2 1 ", hailstones(16));
assertEquals("7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 ", hailstones(7));
}
Those are the test cases. any insight into this would be great. thanks!
You return " " every time the function is called. You need to build up an internal string and return that as result.
I have a homework assignment where I have to covert any base to base 10. I have some given numbers, which are the "basen". I have to convert those bases to base 10. The only part that I am stuck in is this part of the code:
answer = ; // Not sure what I have to put in here
I have seen some other posts about converting to base ten, but I am just not sure how to how to incorporate them into my code.
public class BaseN {
public static final int BASEN_ERRNO = -1;
public static int digit = 0;
public static void main(String[] argv) {
basen(512, 6);
basen(314, 8);
basen(49, 5);
basen(10101, 2);
}
public static void basen(int n, int b) {
int ans = basen(n, b, 1, 0);
if (ans == BASEN_ERRNO)
System.out.println(n + " is not a valid base-" + b + " number");
else
System.out.println(n + " base-" + b + " = " + ans + " base-10");
}
public static int basen(int number, int base, int placevalue, int answer) {
if (number == 0) return answer;
digit = number % 10;
if (digit >= base) return BASEN_ERRNO;
answer = 1;// not sure what to put here
number = 0;
placevalue = 0;
return basen(number, base, placevalue, answer);
}
}
You could look at a k length number of base n like this:
x(0)*n^(k-1) + x(1)*n^(k-2) + ... + x(k-1)*n^1 + x(k)*n^0
Where x(0), x(1), ..., x(k) is the digit at position k from the left.
So, if you are trying to convert, say, 101 base 2 to base 10 you would do the following :
1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 4 + 0 + 1 = 5 base 10
say you want to convert the number 352 from base 6:
3 * 6^2 + 5 * 6^1 + 2 * 6^0 = 108 + 30 + 2 = 145 base 10
What you're looking for code wise is something like this :
int[] digits = {3, 5, 2};
int base = 6;
int answer = 0;
for(int i = digits.length - 1; i >= 0; i--)
{
answer += digits[i] * Math.pow(base,digits.length-i-1);
}
return answer;
which will return 145.
Hopefully even though my implementation is iterative you should be able to apply it to your recursive implementation as well.
You can implement the following algorithm. Lets say you are given String number which represents the number you want to convert to decimal form and int base which represents the base of given number. You can implement function int convertToNumber(char c); which accepts one character representing one digit from your number and will map characters to numbers like this:
0 -> 0,
1 -> 1,
... ,
A-> 10,
B -> 11,
... ,
F -> 15,
...
Then you just iterate through your given string and multiply this functions output with base to the power of iteration. For example, convert number A32(hexadecimal):
A32 = convertToNumber(A) * b ^ 2 + convertToNumber(3) * b ^ 1 + convertToNumber(2) * b ^ 0 = 10 * 16 ^ 2 + 3 * 16 ^ 1 + 2 * 16 ^ 0 = 10 * 16 * 16 + 3 * 16 + 2 = 2610 (decimal).
public class BaseConvert {
public static int convertDigitToNumber(char c) throws Exception {
if(c >= '0' && c <= '9') return c - '0';
if(c >= 'A' && c <= 'Z') return c - 55;
if(c >= 'a' && c <= 'z') return c - 97;
throw new Exception("Invalid digit!");
}
public static int convertToBase(String number, int base) throws Exception {
int result = 0;
for(int i = 0; i < number.length(); i++){
result += convertDigitToNumber(number.charAt(i)) * (int)Math.pow(base, number.length() - i - 1);
}
return result;
}
public static void main(String[] args) {
try{
System.out.println(convertToBase("732", 8));
System.out.println(convertToBase("A32", 16));
System.out.println(convertToBase("1010", 2));
}catch (Exception e) {
System.out.print(e);
}
}
}
When I enter "3" in my java code, it prints
3 will be multiplied by 3 and +1
Value is 10
Any advice as to how I should modify it, so that it calculates the sequences correctly
import javax.swing.*;
public class sequences {
/**
* #param args
*/
public static void main(String[] args) {
calculateSequences();
}//ends main
public static void calculateSequences()
{
int value;
String valueInput = JOptionPane.showInputDialog("Value");
value = Integer.parseInt(valueInput);
if(value == 1)
{
System.out.println("Value is equal to 1, closing down");
System.exit(0);
}
else if ((value%2)==0)
{
System.out.println(value + " will be divided by 2");
value = value/2;
System.out.println("Value is even " + value);
}
else
{
System.out.println(value + " will be multiplied by 3 and +1");
value = 3*value+1;
System.out.println("Value is " + value);
}
}//ends calculateSequences
}//ends class
You forgot the "go to start"
Here are the results from one test.
23 will be multiplied by 3 and + 1
Value is 70
70 will be divided by 2
Value is even 35
35 will be multiplied by 3 and + 1
Value is 106
106 will be divided by 2
Value is even 53
53 will be multiplied by 3 and + 1
Value is 160
160 will be divided by 2
Value is even 80
80 will be divided by 2
Value is even 40
40 will be divided by 2
Value is even 20
20 will be divided by 2
Value is even 10
10 will be divided by 2
Value is even 5
5 will be multiplied by 3 and + 1
Value is 16
16 will be divided by 2
Value is even 8
8 will be divided by 2
Value is even 4
4 will be divided by 2
Value is even 2
2 will be divided by 2
Value is even 1
Value is equal to 1, closing down
Here's your code with a while clause added.
import javax.swing.JOptionPane;
public class Sequences {
/**
* #param args
*/
public static void main(String[] args) {
calculateSequences();
}// ends main
public static void calculateSequences() {
int value;
String valueInput = JOptionPane.showInputDialog("Value");
value = Integer.parseInt(valueInput);
while (value > 0) {
if (value == 1) {
System.out.println("Value is equal to 1, closing down");
System.exit(0);
} else if ((value % 2) == 0) {
System.out.println(value + " will be divided by 2");
value = value / 2;
System.out.println("Value is even " + value);
} else {
System.out.println(value + " will be multiplied by 3 and + 1");
value = 3 * value + 1;
System.out.println("Value is " + value);
}
}
}// ends calculateSequences
}
You need to add iteration or recursion. Since this is Java, it would make most sense to use iteration.
This corresponds to the line "go to start ;" in the algorithm.
For this you can use a while loop, such as while(true).
public static void main(String[] args) {
process(Integer.parseInt(args[0]));
}
private static void process(int n) {
while (n != 1) {
if (n%2 == 0) {
System.out.println(n + " will be divided by 2");
n = n/2;
System.out.println("Value is even " + n);
}
else {
System.out.println(n + " will be multiplied by 3 and +1");
n = 3*n+1;
System.out.println("Value is " + n);
}
}
System.out.println("Value is equal to 1, closing down");
}
And the output:
3 will be multiplied by 3 and +1
Value is 10
10 will be divided by 2
Value is even 5
5 will be multiplied by 3 and +1
Value is 16
16 will be divided by 2
Value is even 8
8 will be divided by 2
Value is even 4
4 will be divided by 2
Value is even 2
2 will be divided by 2
Value is even 1
Value is equal to 1, closing down
How can I write the function to return the difference of the sum of values of nodes at odd height and the sum of values of nodes at even height. Considering the root node is at height 1 for a binary tree
input:
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Output: -74 Explanation :
[ (1 + 4 + 5 + 6 + 7 ) - (2 + 3 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15) = -74 ]
Code:
public static int diff(Node n) {
if (n == null)
return 0;
return Sum(n) - Sum(n.left) - Sum(n.right);
}
public static int Sum(Node root) {
int sum = 0;
if (root == null) {
return sum;
}
sum = sum + root.data;
if (root.left != null) {
sum = sum + Sum(root.left.left) + Sum(root.left.right);
}
if (root.right != null) {
sum = sum + Sum(root.right.left) + Sum(root.right.right);
}
return sum;
}
I have given this solution but not selected... I don't know whats wrong with this.
public static int Sum(Node root) {
if (root == null) {
return 0;
}
return root.data-Sum(root.left)-Sum(root.right);
}
This is easiest and smartest way i found the solution
Here solution is explained using recusrsion in short..
Negate all levels under the current one (the level of the current node) and you do that on each step of the recursion.
sum[l1] – (sum[l2] – (sum[l3] – (sum[l4] – … = sum[l1] – sum[l2] + sum[l3] – sum[l4]…
www.crazyforcode.com/binary-tree-diff-sum-even-nodes-sum-odd-nodes/
How about...
public static int diff(Node n) {
return sumtree(Node n, 1);
}
public static int sumtree(Node n, int level) {
if (n == null) return 0;
if (level % 2 == 0) {
return sumtree(n.left, level + 1) + sumtree(n.right, level +1 ) - n.value;
} else {
return sumtree(n.left, level + 1) + sumtree(n.right, level + 1) + n.value;
}
}
Add values on odd level numbers (1, 3, 5 7...), subtract on even (2, 4, 6, 8...).
The approach I took was to first find a way of adding all of the leaves, then just add a "level factor" if the level is even you you add otherwise you subtract. This may look similar to others but I find it cleaner.
On ANSI C
int diffOddAndEven(Node *root)
{
return sumLevel(root, 0);
}
int sumLevel(Node *root, int level)
{
int sum=0;
int levelFactor = level%2 ? -1 : 1;
if(!root)
return 0;
sum = root->value * levelFactor;
sum += sumLevel(root->left, level+1);
sum += sumLevel(root->right, level+1);
return sum;
}
Check out my solution
traverse(root,1); //1 is passed since we want oddlevelsum - evenlevelsum,pass -1 for opposite
int traverse(Tree* root,int level){
if(root==NULL)return 0;
return (level*root->data)+ traverse(level*-1,root->left_node)
+ traverse(level*-1,root->right_node);
}