To find this particular checksum, we need to sum the digits of the input and multiply by 2. Simple enough by finding the remainder using a loop.
If the result is less than 10, that is the number's checksum. If it is 10 or higher, we need to do it again until the result is less than 10.
If it gets caught in an infinite loop, such as with the input of 18, return -1.
This is what I have so far:
public int getChecksum(int input, int previous) {
int sum = 0;
while (input > 0) {
sum += input % 10;
input /= 10;
}
if (sum * 2 < 10) {
return sum * 2;
} else if (sum * 2 >= 10 && previous != sum) {
previous = sum;
return getChecksum(sum * 2, previous);
} else if (previous == sum) {
return -1;
}
return sum * 2;
}
I really wanted to know if there was a way to do this without doing it recursively as I am doing here.
A rather simple recursive algorithm like this can also be implemented iteratively. Usually you would go about this turning the recursive call into a loop with the recursive termination condition as the loop termination condition.
Related
The code below has no output when I run it, I think somehow it is infinite loop? How to fix it?
Write a method named getEvenDigitSum with one parameter of type int called number.
The method should return the sum of the even digits within the number.
If the number is negative, the method should return -1 to indicate an invalid value.
EXAMPLE INPUT/OUTPUT:
getEvenDigitSum(123456789); → should return 20 since 2 + 4 + 6 + 8 = 20
getEvenDigitSum(252); → should return 4 since 2 + 2 = 4
getEvenDigitSum(-22); → should return -1 since the number is negative
public class getEvenDigitSum {
public static int getEvenDigitSum(int number) {
int sum = 0;
int lastDigit=0;
if (number < 0) {
return -1;
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
return sum;
}
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
OK, and what happens if the number isn't even? You didn't make an else/else if statement after; if your number is odd, it stays the same, the loop is infinite, and hence your code does nothing.
Your condition only handles even digits, but think about what happens when you get a number that contains odd digit, like 1221 for example.
Try adding the missing else statement:
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
else {
// Deal with odd digit, leaving for you to implement
{
}
General tip: The best way to find errors in your code is to write tests and debug your code.
These are two skills every developer should poses and practice regularly
I tried to write a method (for kicks) that would sum up the digits at even places using Java recursion.
For example, the number 23495 would return 3+9 = 12.
I am unsuccessful and would appreciate hints or what I'm doing wrong.
int sumEven = 0;
int sumOdd = 0;
int i = 1;
if (n == 0)
return sumEven;
if (n != 0) {
if (i % 2 == 0)
{
i++;
sumEven += n % 10;
}
else
{
i++;
sumOdd += n % 10;
}
}
return sumEven + getEven (n/=10);
The problem is you're trying to do too much - take a look at my comment on the Q
A recursive method needs an input that contains everything it needs to work with, a return value, and an execution path where it calls itself until something happens that means it doesn't need to call itself any more - without this bit it will recourse until it overflows the stack
int sumEveryOtherDigit(int input){
if(input >= 100)
return input%10 + sumEveryOtherDigit(input/100);
else
return input%10;
}
This takes the input , and if there is any point to running again (if the input is at least 100) takes the rightmost digit plus running itself again with a smaller number
Eventually the number gets so small that there isn't any point running itself again so it just returns without running itself again and that is how the recursion stops
Now from your comment on another answer it seems you want to determine even and odd as working from the left so we need to either start with the number (1630) or the number divided by ten (23495 -> 2349) - basically to start the recursion going we always want to pass in a number with an even number of digits
int num = 23495;
int numOfDigits = (int)Math.log10(num)+ 1;
if(numOfDigits%2==0)
result = sumEveryOtherDigit(num);
else
result = sumEveryOtherDigit(num/10);
You should iterate over the digits of the input number, and then sum the remainder mod 10 only for even position digits:
int input = 23495;
input /= 10;
int sum = 0;
while (input > 0) {
sum += input % 10; // add last even digit
input /= 100; // advance by two digits, to the next even digit
}
System.out.println("sum of even digits of input is: " + sum);
This prints:
sum of even digits of input is: 12
In my computer science class, we were assigned a lab on recursion in which we have to print out a number with commas separating groups of 3 digits.
Here is the text directly from the assignment (the method has to be recursive):
Write a method called printWithCommas that takes a single nonnegative
primitive int argument and displays it with commas inserted properly.
No use of String.
For example printWithCommas(12045670); Displays 12,045,670
printWithCommas(1); Displays 1
I am really stumped on this. Here is my code so far:
public static void printWithCommas(int num) {
//Find length
if (num < 0) return;
int length = 1;
if (num != 0) {
length = (int)(Math.log10(num)+1);
}
//Print out leading digits
int numOfDigits = 1;
if (length % 3 == 0) {
numOfDigits = 3;
}
else if ((length+1) % 3 == 0) {
numOfDigits = 2;
}
System.out.print(num / power(10,length-numOfDigits));
//Print out comma
if (length > 3) {
System.out.print(',');
}
printWithCommas(num % power(10,length-numOfDigits));
}
It gets a stack overflow (which I can fix later), but it fails to print out some of the zeros, specifically the ones that are supposed to be after each comma.
I feel like I am taking this on with a completely wrong approach, but can't think of a good one. Any help would be appreciated.
Thanks in advance!
Note: power is a function I made that calculates power. First argument is the base, second is the exponent.
Here is the code I came up with, for anyone else that might be stuck on this:
public static void printWithCommas(int num) {
if (num > 999) {
printWithCommas(num/1000);
System.out.print(',');
if (num % 1000 < 100) System.out.print('0');
if (num % 1000 < 10) System.out.print('0');
System.out.print(num%1000);
}
else {
System.out.print(num);
}
}
I need to write a code which should calculate the first 200 prime numbers, but I can't hand it in as long as I can't explain everything. I used a piece of code from the internet as reference (http://crab.rutgers.edu/~dhong/cs325/chapter3/PrimeNumber.java).
Whole code:
public class Opdracht3 {
public static void main(String[] args) {
int limiet = 200;
int counter = 1;
int testpriem = 3;
boolean isPriem;
while (counter <= limiet) {
isPriem = true;
for (int i = 2; i <= testpriem / 2; i++) {
if (testpriem % i == 0) {
isPriem = false;
break;
}
}
if (isPriem) {
System.out.println(counter + ": " + testpriem);
counter++;
}
testpriem++;
}
}
}
Below part of code verifies if the number is a composite. If testpriem is composite, then comes out of the loop and starts over. Otherwise, it continues and prints the prime number testpriem.
The problem is here:
for (int i = 2; i <= testpriem / 2; i++) {
if (testpriem % i == 0) {
isPriem = false;
break;
}
}
I tested what happens to i, and one way or another it recognizes the divisor needed to calculate the composite. (With 4 divisor is 2, with 9 divisor is 3, with 221 divisor is 13) But I am flabbergasted as of why.
Any ideas?.
the % or ("remainder") operator in Java divides one operand by another and returns the remainder as its result. And of course if integer x is evenly divisible by another integer y (meaning x/y = some integer z with a remainder of zero), then x can not be prime.
First remember every number able to divide by its half or less. Consider number 7 it is possible divided by 1,2,3 because after 3, if try to divide number by 4 means 4x2 = 8 that is greater than 7. so it is optimum way to find divisor in this way. One more thing every number divided by 1 and number itself. so if number number is divided by 1 or itself then it is called prime so i starts from 2.
now consider testpriem =7 so you will get loop like
for (int i = 2; i <= 7 / 2(i.e 3); i++)
{
if(7 % i == 0)
{
isPriem = false;
break;
}
so first time it checks 7%2=1 so condition false. again check for 7%3 = 1 again condition false. and now this condition full fills here i <= 7 / 2(i.e 3) so loop stopped and it result 7 number is prime
Well, if testpriem % i == 0, it means that i divides testpriem, which means that testpriem is not a prime a number and i, is its first divider. % is the modulo operation, which is the rest of the division.
https://en.wikipedia.org/wiki/Modulo_operation
The break stops the for loop and moves to the next position in the while loop. So it does not restart the for loop for the current tested number.
The break is used for efficiency reasons. You could remove it and the algorithm would still work correctly but slower.
I'm trying to write a simple method in Java that return the reverse of a number (in the mathematical way, not string-wise). I want to take care of boundary conditions since a number whose reverse is out of int range would give me a wrong answer. Even to throw exceptions, I'm not getting clearcut logic. I've tries this code.
private static int reverseNumber(int number) {
int remainder = 0, sum = 0; // One could use comma separated declaration for primitives and
// immutable objects, but not for Classes or mutable objects because
// then, they will allrefer to the same element.
boolean isNegative = number < 0 ? true : false;
if (isNegative)
number = Math.abs(number); // doesn't work for Int.MIN_VALUE
// http://stackoverflow.com/questions/5444611/math-abs-returns-wrong-value-for-integer-min-value
System.out.println(number);
while (number > 0) {
remainder = number % 10;
sum = sum * 10 + remainder;
/* Never works, because int won't throw error for outside int limit, it just wraps around */
if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
throw new RuntimeException("Over or under the limit");
}
/* end */
/* This doesn't work always either.
* For eg. let's take a hypothetical 5 bit machine.
* If we want to reverse 19, 91 will be the sum and it is (in a 5 bit machine), 27, valid again!
*/
if (sum < 0) {
throw new RuntimeException("Over or under the limit");
}
number /= 10;
}
return isNegative ? -sum : sum;
}
Your approach of dividing by 10, transfering the reminder to the current result * 10 is the way to go.
The only thing you are doing wrong is the check for the "boundary violation", because
sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE
can ofc. NEVER be true - Otherwhise MIN and MAX wouldn't have any meaning.
So, think mathematical :-)
sum = sum * 10 + remainder;
should not exceed Integer.MAX_VALUE, i.e.
(!)
Integer.MAX_VALUE >= sum * 10 + remainder;
or transformed:
(!)
(Integer.MAX_VALUE - remainder) / 10 >= sum
So, you can use the following check BEFORE multiplying by 10 and adding the remainder:
while (number > 0) {
remainder = number % 10;
if (!(sum <= ((Integer.MAX_VALUE -remainder) / 10))) {
//next *10 + remainder will exceed the boundaries of Integer.
throw new RuntimeException("Over or under the limit");
}
sum = sum * 10 + remainder;
number /= 10;
}
simplified (DeMorgan) the condition would be
if (sum > ((Integer.MAX_VALUE -remainder) / 10))
which makes perfect sence - because its exactly the reversed calculation of what your next step will be - and if sum is already GREATER than this calculation - you will exceed Integer.MAX_VALUE with the next step.
Untested, but that should pretty much solve it.