Is my understanding of this While Loop correct? - java

The example in the book asks the user to enter any positive number. Then the program will add the individual digits separately and print the total. For example if the user enters the number 7512 the program is designed to add 7 + 5 + 1 + 2 and then print the total.
I've written out the way I understand how the code works. Is this correct? Is my understanding of this loop correct with each step, or am I missing any calculations? What happens during the 4th loop when there is no remainder in 7 % 10?
1st run of loop ... sum = sum + 7512 % 10 which is equal to 2
n = 7512 / 10 which which equals to 751
2nd run of loop ... sum = 2 + 751 % 10 which is equal to 1
n = 751 / 10 which is equal to 75
3rd run of loop ... sum = 3 + 75 % 10 which is equal to 5
n = 75 / 10 which is equal to 7
4th run of loop ... sum = 8 + 7 % 10 <------?
import acm.program.*;
public class DigitSum extends ConsoleProgram{
public void run() {
println("This program will add the integers in the number you enter.");
int n = readInt("Enter a positive integer: ");
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
println("The sum of the digits is" + sum + ".");
}
}

The result of the operation 7 % 10 is 7, the remainder when you divide 7 by 10. The last iteration of the loop is to add 7 to the prior value. The next division step inside the loop (n /= 10;) takes n to 0, which is what ends the loop.

% is not the same as /
The % operator is for the modulus, not division... This means that the result of the operations is not dividing, but obtaining the remainder of the division, like:
7512 % 10 => 2
751 % 10 => 1
75 % 10 => 5
7 % 10 => 7
This kind of logic is fairly frequently used when dealing with numeric operations.

before run, sum = 0, n = 7512
1st run of loop ... sum = 0 + 2 => sum = 2, n = 751
2nd run of loop ... sum = 2 + 1 => sum = 3, n = 75
3rd run of loop ... sum = 3 + 5 => sum = 8, n = 7
4th run of loop ... sum = 8 + 7 => sum = 15, n = 0

After 7%10 you get 7 and that is added to your result.
And 7/10 will result in 0 and hence your loop ends and your sum now has addition that you want.

Related

Question about adding three digits with each other in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a task to add each numbers. One of my colleague helped me out and here's the code.
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
sum = sum + number%10;
number = number/10;
return sum;//write your code here
}
I'm not sure exactly how this works. Can someone please explain to me? Thanks.
You can use within while the loop which will accept any number as #GBlodgett suggested
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
while(number!=0)
{
sum = sum + number%10;
number = number/10;
}
return sum;//write your code here
}
In Java % is the modulo operator. It delivers the remainder of that division. If you divide integer values in Java, any remainder will be lost.
If you add some makeshift logging like that:
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
sum = sum + number % 10;
number = number / 10;
System.out.println(number);
return sum; // write your code here
you will get the following output:
54
5
0
15
546 % 10 = 6
546 / 10 = 54
54 % 10 = 4
54 / 10 = 5
5 % 10 = 5
5 / 10 = 0
sum = 6 + 5 + 4 = 15
Your code will only work up to three digits. If you transfer the sequence of modulo and division operations into a loop it will be a generic solution.
The JVM(Java Virtual Machine) starts executing your code and public static void
main(String[] args) is the starting point.
Then executes System.out.println(sumDigitsInNumber(546));
System.out.println() is a method that prints the argument passed, into the System.out which is generally stdout (Standard output). The argument passed is the sumDigitsInNumber(546) method, hence it would print what sumDigitsInNumber() would return.
sumDigitsInNumber() initializes a sum variable with 0 to store the sum of 546.
sum = sum + number%10 gives you 6 (0 + 6), where number%10 gives
the last digit of 546 which is 6
number = number / 10 will replace number by 54 because 546/10 is 54.6 since it is an integer division .6 is ignored and 54 is stored in the number.
Repeat the above step twice but the number being 54 and then 5.
return sum returns the sum to the caller which is your main() method, hence System.out.println() printing the sum of 546.
Step by step:
this creates variable named sum and assigns it value of 0:
int sum = 0;
this does the following:
it assigns to variable 'sum' the result of sum + number % 10 (where a number is an argument passed to the method)
sum = sum + number%10;
number % 10 is in your example a remainder of 456 / 10, so in 456, you can pack number 10 exactly 45 times, whatever is left that is less then 10 is your result (remainder), in this case 6.
see http://www.cafeaulait.org/course/week2/15.html
next we divide current number by 10:
number = number / 10;
so 456 / 10 = 45.6
and as the type of variable is int - it is actually 45 (as int always rounds down the remainder) - see Int division: Why is the result of 1/3 == 0?
then it is being repeated 2 times until all 3 digits are summed up.
Notice, that your method will only work for 3 digit numbers. That's not that good.
You can easily make your method to work with any digits length int number passed.
Hint: use loops!
As you can see, you're repeating the same piece of code 3 times.
You could place it inside a loop and make it execute as many times as there are digits in your number.
something along these lines, but you need to figure out when to stop the while loop!
int sum = 0;
while (?WHEN TO EXIT?) {
sum = sum + number % 10;
number = number / 10;
}
Think about when you can exit loop (when, in example, maybe this number variable that you divide by 10 each iteration can tell you that all digits have been processed?)
Here is a solution that computes the sum of a number, no matter how many digits it has:
Generally speaking, a number has exactly [log(number)+1] digits, the tempInt variable is introduced to store the parameter value, it is considered a bad practice to modify the values of the method parameters :
public static int sumOfDigits(int number) {
int sum = 0;
int length = (int) Math.ceil(Math.log10(number));
int tempInt = number;
for (int i = 0; i < length; i++) {
sum += tempInt % 10;
tempInt /= 10;
}
return sum;
}
public class Solution {
public static void main(String[] args) {
System.out.println(sumDigitsInNumber(546));
}
public static int sumDigitsInNumber(int number) {
int sum = 0;
sum = sum + number%10; // number%10 = the last digit of 546 (= 6), sum = 0 + 6
number = number/10; // number = number whithout the last digit (54)
sum = sum + number%10; // number%10 = the last digit of 54 (= 4), sum = 0 + 6 + 4
number = number/10; // number = number whithout the last digit (5)
sum = sum + number%10; // number%10= the last digit of 5 (= 5), sum = 0 + 6 + 4 + 5
number = number/10; // number = number whithout the last digit (useless)
return sum;//sum = 6 + 5 + 4 = 15
}

Arithmetic Operations -Java

class Example {
public static void main(String args[]){
System.out.println(12+8/5%4*(5-4/5)+4*5);
}
}
Why the output is 37? Can anyone explain? I'm a beginner in java
Check the precedence of the operators in java:
12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0)+4*5
12+8/5%4*5+4*5
12+1%4*5+4*5
12+1*5+4*5
12+5+20
37
You have: 12+8/5%4*(5-4/5)+4*5
In the post of user3134614
12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0)
12+8/5%4*5+4*5
12+1%4*5+4*5
12+1*5+4*5
12+5+20
37
You have the basic operators
+ add two numbers
- subtract two numbers
* Multiply two numbers
/ divide two numbers
And these, a little more advanced
% gets the remainder of two numbers, that is, that divides them and obtains the remainder, if the number is even, then the rest is zero, and if it is odd, it is another number
For example 4%4 would be 4 divided by 4 results in 2 and 2 + 2 = 4, there is no remainder, on the other hand 5%4 = 1, because 2 + 2 = 4 and over 1 of 5
The parentheses () separate a mathematical expression and return it as a single quantity, example
5 - (3-2) * 2 is equivalent to 5 - (1) * 2 = 5 - 2 = 3
Then
12+8/5%4*(5-4/5)+4*5
12+8/5%4*(5-0) is 12+8/5%4*(5 - (4/5) = 0.8, but converted to integer is 0, then 5 - 0 = 5)
12+8/5%4*5+4*5 is 12+ (8/5 = 1.6, but to integer is 1) %4*5+4*5
12+1%4*5+4*5 is 12+ (1%4 = 1 (1 is different of 4 then result is 1)) *5+4*5
12+1*5+4*5 is 12 + (1*5 = 5) + (4*5 = 20)
12+5+20 and 12 + 5 + 20 = 37
37

Given a singly linked list how to find the mod of it with a number

Given a decimal number represented as list from least significant bit to most significant bit how should one find mod with k if the list were a number.
Example :- number - 1234567
list representation of number: 7->6->5->4->3->2->1
k = 7
ans = 1234567%7 = 5
In python and java I could have converted the list to a number BigInteger(java) and have taken the mod. But I wanted to do it without using BigInteger.
I have tried calculating the mod while iterating the list
total=0
for digit in numberList:
total = (total * 10 + digit) % k
return total
But this is not going to work.
You can calculate the remainder of the i'th digit multiplied by 10^i for each digit. Then sum all these remainders and find the remainder of the sum :
int mul = 1;
int remainder = 0;
for (int digit : digitArray)
{
remainder += (digit * mul) % k;
mul *= 10;
}
remainder = remainder % k;
For 1234567%7, this loop basically computes :
(7 % 7 + 60 % 7 + 500 % 7 + 4000 % 7 + 30000 % 7 + 200000 % 7 + 1000000 % 7) % 7 =
(0 + 4 + 3 + 3 + 5 + 3 + 1) % 7 = 19 % 7 = 5
Your code is close, but you need to process your number list in reverse. I'll illustrate with a simple Python list.
num = 1234567
# Construct numberList
numberList = []
n = num
while n:
n, d = divmod(n, 10)
numberList.append(d)
k = 7
print(num, numberList, num % k)
# Find numberList mod k
r = 0
for d in reversed(numberList):
r = (10 * r + d) % k
print(r)
output
1234567 [7, 6, 5, 4, 3, 2, 1] 5
5
Think of the basic property of modular arithmetic :
(a*b)%m=(a%m * b%m ) % m
(a+b)%m=(a%m + b%m ) % m
Now, to find modulo of 1234567
1234567 % m = (1234 * 1000 + 567)%m
=((1234 * 1000)%m + 567%m) %m
Now, take a little small no. to better understand this trick
12345 =( ( (1 * 10 + 2) * 10 + 3) * 10 + 4) *10 +5
Now,
12345 % m = (((((((1*10)%m + 2)*10)%m + 3)*10)%m + 4)*10 + 5)%m
Now to find modulo of a number that is represented by a linked list its actually easy
list1: 1->2->3->4->5.......
take variable result and initialize with 0
i.e., result=0 and just traverse the list and do:
result = (result*10 )% m + node->data
see the code below it is too simple
int result=0;
while(list1){
int x=list1->data;
result=(result*10)%m + x;
list1=list1->next;
}
result=result%m;
return result;

Solve equation in Java with modulo

I need to solve this equation in my Java app:
(1080 * j + 1) modulo 7 = 0
Is there some more safe way how to get this value instead of this code? I am not much happy with while loop condition.
int j = 1;
int e = 7;
boolean found = false;
double r = 0;
while (!found) {
r = (1080 * j + 1);
found = r % e == 0;
j++;
}
int t = (int) (r / e);
You can improve your solution significantly using maths. You need to find a number that multiplied by 1080 will given a remainder 6 modulo 7 (because after adding 1 it should be divisible by 7). Now 1080 gives remainder 2 modulo 7. Thus you need to find number that multiplied by 2 gives 6 modulo 7. Lets check all 7 possible remainders:
0 * 2 = 0 (modulo 7)
1 * 2 = 2 (modulo 7)
2 * 2 = 4 (modulo 7)
3 * 2 = 6 (modulo 7)
4 * 2 = 1 (modulo 7)
5 * 2 = 3 (modulo 7)
6 * 2 = 5 (modulo 7)
So the only solutions to your problem are the numbers giving remainder 3 (modulo 7) and all such numbers are solutions of the equation.
(1080*j + 1)% 7 =((1080*j)%7 + 1%7 )%7
And (1080*j)%7 = ((1080%7)*(j%7))%7 = (2*(j%7))% 7
And actually, j only need to run from 0 to 6, as you can clearly see that this is a periodic cycle, which help you to avoid infinite loop, as well as any number (not necessary 7)
(1080*j+1) mod 7 = 0 => 1080*j = 1 (mod 7). So you can use For loop from 0 to 6 like this :
int j;
for(int i=0; i<7; i++){
if((1080*i) % 7==1) {
j=i; break;
}
}
Here is a way to simplify the equation :-
(1080*j + 1)mod 7 = 0
(1080*j)mod7 = 6
by multiplication theorem of modular arithmetic : -
(a*b)%k = (a%k * b%k)%k hence (1080*j)%7 = (1080%7 * j%7)
1080%7 = 2
hence (1080*j)%7 = (2* j%7)%7 = 6
Now j%7 could have values (0,1,2,3,4,5,6)
now of all possible values j%7 = 3 would give (2*3)%7 = 6
j%7 = 3
therefore j = k*7 + 3 is solution to equation where k is any whole
number

Can someone explain the following method that is used to find the length of the repeating cycle or period of a repeating decimal?

After reading information off the Wikipedia page for repeating decimals, I have found a way to find the number of digits in the repeating part of a decimal.
For example,
1/3 = 0.333333333333333333333333333333... so the result is 1 digit.
1/7 = 0.142857142857142857142857142857... so the result is 6 digits.
However, my method (in Java) did not work for 1/6 which should yield 1 because:
1/6 = 0.1666... so the result is 1 digit despite the non-repeating part of the decimal.
I have found a solution that works (credit to Nayuki Minase).
private static int getCycleLength(int n)
{
Map<Integer,Integer> stateToIter = new HashMap<Integer,Integer>();
int state = 1;
int iter = 0;
while (!stateToIter.containsKey(state))
{
stateToIter.put(state, iter);
state = state * 10 % n;
iter++;
}
System.out.println(iter + " - " + stateToIter.get(state));
return iter - stateToIter.get(state);
}
Can someone please explain to me how this algorithm works? Thank you.
Nayuki here. The code is from Project Euler p026.java. Let me explain what's going on.
The main idea is that we simulate long division and detect when the remainder starts repeating. Let's illustrate with an example of computing 1/7.
0.142857...
-------------
7 | 1.000000000
7
---
30
28
--
20
14
--
60
56
--
40
35
--
50
49
--
10
...
To perform long division, we perform these steps:
Set divisor = 7. Set dividend = 1. (We are computing 1/7.)
----
7 | 1
How many times does the divisor go into the dividend? Let this be k. Append this digit to the quotient.
0
---
7 | 1
Subtract k × divisor from the dividend. This is the remainder.
0
---
7 | 1
-0
--
1
Shift in a new digit on the right side. In our case, it's an infinite decimal of zeros. This is equivalent to multiplying the dividend by 10.
0
---
7 | 1.0
-0
--
10
Go to step 2 and repeat infinitely.
0.1
-----
7 | 1.0
-0
--
10
-7
--
3
...
We update the dividend in every iteration of long division. If the dividend takes on a value that it previously did, then it will generate the same decimal digits.
Now, in code:
// Step 1
int divisor = 7;
int dividend = 1;
while (true) {
// Step 2
int k = dividend / divisor; // Floor
// Step 3
dividend -= k * divisor;
// Step 4
dividend *= 10;
}
With a bit of math, steps 2 and 3 can be combined as dividend %= divisor;. Furthermore, this can be combined with step 4 to get dividend = dividend % divisor * 10;.
The map keeps track of the first time each dividend state was seen. In our example:
The remainder 1 was seen at iteration 0.
The remainder 3 was seen at iteration 1.
The remainder 2 was seen at iteration 2.
The remainder 6 was seen at iteration 3.
The remainder 4 was seen at iteration 4.
The remainder 5 was seen at iteration 5.
The remainder 1 was seen at iteration 6.
The state at iteration 6 is the same as the state at iteration 0. Furthermore, this is the shortest cycle. Hence, the cycle length is 6 − 0 = 6.
So in this algorithm this line is the key.
while(!stateToIter.containsKey(state))
It is breaking the program when it found a repetitive state. Now finding a repetitive state means we are detecting a repeating cycle. Lets go through the problem, say we have to find out for 6.
The way we do 1 / 6 is
Problem :6 | 1 | Result = ?
Step 1:
Add 0. in the result and multiply 1 with 10
6 | 10 | 0.
Iteration
Step 2:
Do the division
6 | 10 | 0.1
6
-----
4 [Mod]
Iteration = 0
Step 3:
Multiply mod with 10 and carry on
6 | 10 | 0.16
6
-----
40
36
-----
04 [Mod]
Iteration = 1
Now we find a repeating mod so now matter how far we go we always get 4 as mod and our result will be 0.166666.. and so on so our repeating cycle will be 1 which is our iteration.
When conventing to decimal you progressively multiply the value you have by 10 until you either have 0 (no more to write) or give up (you have reached the limit of your precision)
Once you have the same value you are working on again, you will repeat the same digits from that point. What the method does is find when you get a repeating values and computes how long it have been since you first saw it (the length of the repeating cycle)
BTW Another solution to this problem which avoids using a Map. Any repeating sequence must be a multiple of 1/9 or 1/99 or 1/999 or 1/9999 etc. This finds how many nines is required for the divisor to be a factor. This is the point at which it repeats.
public static void main(String... args) throws IOException {
for (int i = 3; i < 100; i++) {
System.out.println("i: " + i + " f: " + 1.0 / i + " repeat: " + getRepeatingCount(i));
}
}
public static final BigInteger TEN_TO_19 = BigInteger.TEN.pow(19);
public static int getRepeatingCount(int divisor) {
if (divisor <= 0) throw new IllegalArgumentException();
while (divisor % 2 == 0) divisor /= 2;
while (divisor % 5 == 0) divisor /= 5;
int count = 1;
if (divisor == 1) return 0;
for (long l = 10; l > 0; l *= 10) {
long nines = l - 1;
if (nines % divisor == 0)
return count;
count++;
}
for(BigInteger bi = TEN_TO_19; ; bi = bi.multiply(BigInteger.TEN)) {
BigInteger nines = bi.subtract(BigInteger.ONE);
if (nines.mod(BigInteger.valueOf(divisor)).equals(BigInteger.ZERO))
return count;
count++;
}
}

Categories

Resources