I do not understand why the recursion problem of this code I wrote works, below I will show what the function that is used in the code below from the library used in my university
void multiplyBy10(int k)
Multiplies this by 10 and adds k.
Parameters:
k - the int to be added
Updates:
this
Requires:
0 <= k < 10
Ensures:
this = 10 * #this + k
and divideBy10 simply divides the natural number by 10 and returns the remainder and NaturalNumber.RADIX is simply a constant equal to 10.
private static void decrement(NaturalNumber n) {
assert n != null : "Violation of: n is not null";
assert !n.isZero() : "Violation of: n > 0";
int digit = n.divideBy10();
digit = digit - 1;
if (digit == NaturalNumber.RADIX) {
digit = 0;
decrement(n);
} else if (digit < 0) {
digit = 9;
decrement(n);
}
n.multiplyBy10(digit);
}
Now the code does work, if you input any number it will decrease it by 1, although I am a bit confused as to why
First of all. Thats exactly the reason why classes like NaturalNumber should be immutable. Using a static method for applying changes on an instance is a violation of the open-closed-principle.
'int digit = n.divideBy10();' changes the value of n. Otherwise this method would not terminate.
I assume that you call 'n.multiplyBy10(-1)'. This would explain the correct result for numbers<10.
Which input arguments have you tested for this method?
Related
Not sure if anyone can explain this to me or help me.
I have a 15 Digit Number of which I want to multiply each even number by 2 unless the even number is greater than 9. If it is this needs to be subtracted by 9 to give me an integer that again I can multiply by 2. Once I have all the even numbers multiplied by 2 i need to add them all together with the odd numbers.
Does that make sense.
UPDATE ***
so i have a number say 49209999856459. for that number I am looking to get the even integer so for example the first even one would be 4 then the second would be 2 and so on.
If one of those even numbers are multiplied by 2 then it might be above 9 so I want to subtract 9 to then use the remainder as the even number in its place.
SO !!!
Multiply by 2 the value of each even digit starting from index 0 and then each even index. In each case, if the resulting value is greater than 9, subtract 9 from it (which reduces larger values to a single digit). Leave the values of the digits at the odd indexes unchanged.
public String calculateCheckNumber()
String firstFifteen = longNumber.substring(0,15) ;
int i, checkSum = 0, totalSum = 0;
for (i = 0; i<firstFifteen.length(); i += 2) {
while (i < 9)
i *= 2;
if (i > 9)
i -= 9 ;
}
Was one option I was trying but it honestly I cant seem to get my head around it.
Any Help would be greatly appreciated.
Well, here is one approach. This uses the ternary (?:) operator to condense the operations. Edited base on clarification from the OP. The example you gave is actually a 14 digit string. But the following will work with any number of digits if they start out in a string. If you have a long value, then you can create the character array using:
long v = 49209999856459L;
char[] d = Long.toString(v).toCharArray();
Here is the main algorithm.
String s = "49209999856459";
int sum = 0;
char[] d = s.toCharArray();
for (int i = 0; i < d.length; i++) {
int v = d[i] - '0';
// The even digit will only be greater than 9 after
// doubling if it is >= 5 before.
sum += ((i % 2) == 1) ? v : (v >= 5) ? v+v-9 : v+v;
}
System.out.println(sum);
Prints
86
I am a very new student. I have a coding exercise that I've been trying to get through, and I thought my solution was functional, but I am getting unexpected results. I'm wondering if there is a problem with my logic?
Assignment: Write a method named sumFirstAndLastDigit with one parameter of type int called number.
The method needs to find the first and the last digit of the parameter
number passed to the method, using a loop and return the sum of the
first and the last digit of that number.
If the number is negative then the method needs to return -1 to
indicate an invalid value.
Example input/output
sumFirstAndLastDigit(252); → should return 4, the first digit is 2 and the last is 2 which gives us 2+2 and the sum is 4.
sumFirstAndLastDigit(257); → should return 9, the first digit is 2 and the last is 7 which gives us 2+7 and the sum is 9.
sumFirstAndLastDigit(0); → should return 0, the first digit and the last digit is 0 since we only have 1 digit, which gives us 0+0 and the
sum is 0.
sumFirstAndLastDigit(5); → should return 10, the first digit and the last digit is 5 since we only have 1 digit, which gives us 5+5 and the
sum is 10.
sumFirstAndLastDigit(-10); → should return -1, since the parameter is negative and needs to be positive.
NOTE: The method sumFirstAndLastDigit needs to be defined as public
static like we have been doing so far in the course.
NOTE: Do not add a main method to solution code.
Here is what I came up with (I've included just the method itself):
public static int sumFirstAndLastDigit (int number) {
if (number < 0) {
return -1;
} else if (number <= 9) {
number += number;
return number;
}
int num = number;
int sumFirstAndLast = 0;
while (num > 0) {
int useDigit = (num % 10);
if ((num == number) || ((double)num < 1)) {
sumFirstAndLast += useDigit;
}
num = num / 10;
} return sumFirstAndLast;
}
I think the issue might be the if statement in my while loop - but I'm not sure. I want it to check if num is equal to the original number that gets passed to the method, and check after num has been run through the while loop a few times, check if it's less than 1 (which is why I cast it as a double)
When I write out how each loop should run, it seems like it would work, but I've been getting incorrect output.
Any help, critiques, rules of thumb, etc. are greatly appreciated. Thanks in advance.
You can do something like this
public static int sumFirstAndLastDigit (int number) {
int first = number;
while (first >= 10) {
first /= 10;
}
int last = number % 10;
return (first + last) >= 0 ? (first + last) : -1;
}
It gets frist and last number from the input and sums them together, then in the return you check if it was a negative number, then you return -1.
The method written in the below code needs to take integer and result sum of 1st digit and last digit in the integer.
NOTE: The reason i am asking this question though i got to know the correct solution is i need to understand why my code is not working also as that makes me a better programmer please help.
public class FirstLastDigitSum {
public static int sumFirstAndLastDigit(int number)//to add first and last
//digits of a given interger
{
int firstdigit=0;
int lastdigit=0;
if(number>=0 && number<=9)
{
return number+number;
}
else if(number>9)
{
lastdigit=number%10;
while(number>0)
{
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
}
return firstdigit+lastdigit;
}
else
return -1;
}
public static void main(String[] args)
{
System.out.println(sumFirstAndLastDigit(121));
}
}
In the above code if i keep number/=10 after if block like below
if(number<=9 & number>=0){
firstdigit=number;
}
number/=10;
then my code is giving proper results. like if i input 121 to the method as first digit is 1 and second digit is 1 it is summing both and giving me result 2. which is absolutely correct
But if keep number/=10 above the if block like below
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
Then my code is not giving proper result it is giving only last number which is 1.
I am not at all understanding why this is happening can any one explain please.
Lets break this up into two parts. Get the last digit of the number, and getting the first digit of the number.
The first part of the problem is easy. Its exactly what you already have; just take modulo 10 of the number.
int lastdigit = number % 10;
The second part is a little trickier, but not too much. While the number is greater than 10 divide it by 10 (using integers you will have truncation for the remainder). One problem I see in your solution is that you keep checking the value even after a digit is discovered. That means if the value was 1234, you correctly find 1, but then overwrite it to 0 with an extra loop iteration
int firstdigit = number;
while (firstdigit >= 10) {
firstdigit /= 10;
}
And that's it, you are done. Just return the value.
return firstdigit + lastdigit;
If the number is less than 0 then return -1. Otherwise the last number can be found by modulus 10, and the first number found by dividing by 10 until that number is less than 10.
public static int sumFirstAndLastDigit(int number) {
if (number < 0) {
return -1;
}
int last = number % 10;
int first = number;
while (first >= 10) {
first = first / 10;
}
return first + last;
}
In this case:
while(number>0)
{
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
}
Note that you change number after you check number > 0. That means that number can be 0 when reaches the if statement and if it is 0 it will be accepted as first digit because it satisfies the condition number<=9 & number>=0. As an example, when you test it with 121 you have this values for number 121, 12, 1 and 0. The last one satisfies the if statement and set first digit to 0.
In this case:
while(number>0)
{
if(number<=9 & number>=0){
firstdigit=number;
}
number/=10;
}
You change number before you check number > 0. That means that the if statement will never have a number = 0 and firstdigit will never be 0. As an example, when you test it with 121 you have this values for number 121, 12, and 1. The last one satisfies the if statement and set first digit to 1. After that you divide number by zero and it becomes 0 and it stop the while loop.
This is not a direct solution to your problem, but we can fairly easily handle this using regex and the base methods:
int number = 12345678;
String val = String.valueOf(number);
val = val.replaceAll("(?<=\\d)\\d+(?=\\d)", "");
number = Integer.parseInt(val);
int sum = number % 10 + number / 10;
System.out.println(sum);
the question is "Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit."
public static void main(String[] args){
System.out.println(persistence(39));
//System.out.println(persistence(999));
}
public static int persistence(long n) {
long m = 1, r = n;
if (r / 10 == 0) {
return 0;
}
for(r = n; r!= 0; r /=10){
m *= r % 10;
}
//System.out.println(m);
return persistence(m) + 1;
}
I understand that the if statement is for when its finally a single digit and it'll return 0. If i could get an explanation on the m variable and what its there for. What the for loop does and when it returns persistence(m) why there is a + 1 on it.
The calculation will comes likes this .
let us understand the problem statement.
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of
times you must multiply the digits in num until you reach a single
digit."
Say : 39
which is the number of times you must multiply the digits in num
until you reach a single digit.
So, we need to do like this to satisfy the above statement.
39 = 3*9 = 27 (1 time) - persistance(39)
27 = 2*7 = 14 (2rd time) - persistance(27)
14 = 1*4 = 4 (3rd time)- persistance(14)
So, according to the problem statement we come to the single digit.
you can take reference of the below, understand it .
why there is a + 1 on it.
to count the number of times the recursive function done the calculation.
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.