Methods That Return Values Quiz - java

I am super new to programming and I had a question on a quiz and the output answer was 36. I don't understand how that outcome came out of this code.
public class Method {
public static int method(int number) {
int result = 0;
while ( number > 0) {
result += number % 10;
number = number / 10;
}
return result;
}
public static void main (String[] args) {
System.out.println(method(9999));
}
}

Clearly within this code the part we need to look at is the while loop, this is the area of interest because it's where all of the calculation occurs.
while(number > 0){
result += number % 10;
number = number/10;
}
So the first line within the loop will add a value to the result:
result += number % 10;
The % operator in Java and many other languages can be thought of as a remainder of division, hence we are adding the remainder of division by 10 to the result.
9999 / 10 = 999 remainder 9.
So result has 9 added.
Then we call:
number = number / 10;
In Java when dividing an int we do not consider the remainder, so 9999/10 = 999.
And then we repeat. So essentially we are adding up the digits of the number.
9 + 9 + 9 + 9 = 36.

Even if you are new at programming, you could try to use an IDE like Eclipse.
Using an IDE you can use the breakpoints and follow the code line by line and the variable line by line. So you will understand what happens.
You could create a watch expression that will show on a tab the variable to you or use the inspect to do this.
A video: https://www.youtube.com/watch?v=drk_ldaRMaY

Related

Java Basics - Extract digits from a number

I'm new to Java, so still trying to figure out the syntax and code execution,
I'm working on a very simple algorithm which is basically to return/print true or false statement if a number is divisible by the sum of its digits.
public class Main {
public static void main(String[] args) {
divisableNumber();
}
static void divisableNumber() {
int num = 2250;
int sumOfDigits = 0;
while (num > 0) {
System.out.println(num);
int remainder = num %10 ;
sumOfDigits += remainder;
System.out.println("line17");
System.out.println(sumOfDigits);
num = num /10;
}
System.out.println(num);
// if(num % sumOfDigits == 0) {
// System.out.println( num);
// } else {
// System.out.println(num + "is not divisable by sum of digits");
// }
}
//*****Explanation*********
// java divides by 10 without remainder.
// Hence, can see that with each iteration number is losing its unit digit( it happens end of each loop line21)
// basically with each iteration we are checking what is the remainder of the input divided by 10
// Eventually, we are adding the remainder ( which is the unit digit at each iteration)
}
``
I don't understand why the loop zeros out the variable and how to overcome it ( i could have written another variable inside the loop , but it seems not clean ).
Can anyone help ?
[enter image description here][1]
[1]: https://i.stack.imgur.com/rZbOW.png
Your code prints 0 every time since it divides the number to 10 until it becomes 0 inside the while loop. Remember that any positive number below 10 divided by 10 gives the result 0 in Java.
You calculated the sum of digits correctly but did not check if it divides the number correctly. In order to achieve that, you need to store a copy of number at the start and check if it is divisible by sumOfDigits.
You can achieve the solution with the following code, it is very similar but structured a little better.
class Main
{
// Function to check if the
// given number is divisible
// by sum of its digits
static String divisableNumber(long n)
{
long temp = n; // store a copy of number
// Find sum of digits
int sum = 0;
while (n != 0)
{
int k = (int) n % 10; // get remainder of division of 10
sum += k; // add digit sum
n /= 10; // divide number by 10
}
// check if sum of digits divides n
if (temp % sum == 0)
return "YES";
return "NO";
}
// This is where the execution begins always (main function)
public static void main(String []args)
{
long n = 123; // better to declare number here and give it as a parameter to function
System.out.println(isDivisible(n)); // print the result of divisible or not
}
}

How many bases b are there such that the base b representation of number starts with a 1?

The problem statement is :
Problem Statement-: Altaf has recently learned about number bases and is becoming fascinated.
Altaf learned that for bases greater than ten, new digit symbols need to be introduced, and that the convention is to use the first few letters of the English alphabet. For example, in base 16, the digits are 0123456789ABCDEF. Altaf thought that this is unsustainable; the English alphabet only has 26 letters, so this scheme can only work up to base 36. But this is no problem for Altaf, because Altaf is very creative and can just invent new digit symbols when she needs them. (Altaf is very creative.)
Altaf also noticed that in base two, all positive integers start with the digit 1! However, this is the only base where this is true. So naturally, Altaf wonders: Given some integer N, how many bases b are there such that the base-b representation of N starts with a 1?
Input Format :
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Each test case consists of one line containing a single integer N (in base ten).
Output Format :
For each test case, output a single line containing the number of bases b, or INFINITY if there are an infinite number of them.
Constraints:
1 <= T <= 10^5
0 <= N < 10^12
Sample Input
4
6
9
11
24
Sample Output:
4
7
8
14
Explanation:
In the first test case, 6 has a leading digit 1 in bases 2, 4, 5 and 6: 610 = 1102 = 124 = 115 = 106.
I trying this in java , But at some point my loop is not working it only takes the first value and after that it will come out of the loop!! Thank you
My code :
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
long n,i,j,k,m;
long count=0,rem1,index;
long rem[];
rem = new long[(int)100];
int t = sc.nextInt();
for(i=1;i<=t;i++)
{
n = sc.nextInt();
j=2;
while(j<=n)
{
// for(j=2;j<=n;j++)
// {
index=0;
m = j;
while(n>0)
{
rem1 = n%m;
rem[(int)index++] = rem1;
n = (long) (n / m);
}
// for(k=index-1;k>=0;k--)
// {
if(rem[1]==1)
{
count++;
}
// }
j++;
}
System.out.println(count);
// }
}
}
}
I'm not sure I follow the logic in the loop (and, by your own admission, there's a problem there).
The logic of the loop (i.e., "how many bases represent the number N with a representation starting by 1"), can be greatly simplified.
The first step is finding the highest power of the base B required to represent the number N. This is given by logb(n), truncated to the nearest integer. Java doesn't have a built-in log function with a variable base, but you can get this result by calculating log(n)/log(b).
Then, you need to find the digit in this position. This can be calculated by dividing N by Bpower using integer division.
From there on, you just need to check if the result is 1, and if so, record it.
Put it all together and you'll end up with something like this:
private static int howManyBasesStartWithOne(int num) {
int count = 0;
for (int i = 2; i <= num; ++i) {
int highestBase = (int) (Math.log(num) / Math.log(i));
int leadingDigit = num / (int) Math.pow(i, highestBase);
if (leadingDigit == 1) {
++count;
}
}
return count;
}

I need help understanding this recursive code

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.

Euler Challenge 1 in Java - I'm doing something wrong?

http://projecteuler.net/problem=1
Hey. I'm a high schooler trying to get a good grasp on programming problems, so I visited Project Euler. For Problem 1, I wrote up some code in Java that would of solved it, but something is evidently going wrong. Can I get some insight as to what?
Explanation:
I stop everything at the index value of 332 because Java counts from 0, and 333 * 3 is 999 which is below 1,000. Apples is a seperate class with pretty much the same code, although it counts for 5. At the end, I manually add together the two answers, but it wasn't right. What am I doing wrong?
The two final sums are:
Three: 164838
Five: 97515
public class Learning {
public static void main(String[] args){
int three[] = new int[333];
int counter = 0;
three[332] = 0;
int totalthree = 0;
int threeincrementer = 1;
int grandtotal;
boolean run = true;
boolean runagain = true;
for (counter = 1; counter<=332; counter++){
three[counter] = 3 * counter;
if (!(three[332] == 0)){
System.out.println("Finished three.");
while (run == true){
totalthree = totalthree + three[threeincrementer];
threeincrementer++;
if (threeincrementer >= 332){
run = false;
System.out.println("Three final is: " + totalthree);
}
}
}
if (runagain == true){
apples ApplesObject = new apples();
ApplesObject.rerun(0);
runagain = false;
}
}
}
}
Some numbers are at the same time multiplication of 3 AND 5 like 15 so you shouldn't separately calculate sum of all multiplications of 3 and multiplications of 5 and than add them because you will end up doing something like
sum3 = 3,6,9,12,15,...
sum5 = 5,10,15,...
so first sum3 will include 15, and sum5 will also include it which means you will add 15 two times. Now to balance your calculations you will need to subtract from your sum3+sum5 sum which will add all multiplications of 15
sum15 = 15,30,45,...
So using your approach your final formula should look like sum3+sum5-sum15.
But simpler solution for this problem can look like
sum = 0
for each X in 1...999
if (X is multiplication of 3) OR (X is multiplication of 5)
add X to sum
To check if some number X is multiplication of number Y you can use modulo operator % (example reminder = X % Y) which finds the remainder of division of one number by another.
You can find more Java operators here

Why is my solution to project euler 1 not working?

I decided to just try and get the small example of only going to 10 like the example shown.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 >and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
public class project1 {
public static void main(String[] args) {
int three=0;
int tot3=0;
int five=0;
int tot5=0;
int total;
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
while (tot5<10) {
five+=5;
tot5=tot5+five;
};
total=tot3+tot5;
System.out.println("Three's: " + tot3);
System.out.println("Five's: " + tot5);
System.out.println("Combined: " + total);
}
}
My output is as show:
Three's: 18
Five's: 15
Combined: 33
Numbers that are both multiples of 3 and 5 (like 15 for instance), are counted twice - once in each loop.
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
I think you mean
while (tot3<10) {
three += tot3; // Add this multiple of 3 to the total.
tot3+=3; // increment the "next multiple"
}
(same for 5)
Lone nebula also makes a good point - you'd need to add logic to the "5" loop to check it's not already counted in the 3 loop. The mod (%) operator can help there.
First,
while (tot3<10) {
three+=3;
tot3=tot3+three;
};
while (tot5<10) {
five+=5;
tot5=tot5+five;
};
This should be
while (three<10) {
three+=3;
tot3=tot3+three;
};
while (five<10) {
five+=5;
tot5=tot5+five;
};
Because you're concerned about when you start counting numbers above 10, not when your TOTAL of those numbers is above 10.
Secondly, your solution will count numbers that are a multiple of three and of five twice. For example, 15 will be added twice. Learn about the modulo operator, %, to come up with a solution to this (for example, not adding five to the tot5 count if five % 3 == 0)
I would recommend looking into using the modular operator to solve this problem. In java % will allow you to perform modular arithmetic. For example any multiple of 3 such as 9 % 3 = 0 while 9 % 2 = 1. It can be thought of as what remains after you divide the first number by the second. All multiples of a number modded by that number will return zero.
Keep track of your variables through the loop and you'll see the problem:
for tot3
=3
=9
=18
=30
You're keeping track of the sum, instead of tracking the multiples. This problem is partially solved in by
while(three<10)
Again, keeping track of the variable through the loop you'll see that this is wrong- it stops at 12, not 9 as you want it. Change it to
While(three<9)
//ie the last divisible number before the limit, or that limit if its divisible (in the case of 5)
All said, an infinitely more elegant solution would involve modulus and a nice little if statement. I hope this helps!
public class project1 {
public static void main(String[] args) {
int number = 0;
int total = 0;
while (number < 10) {
System.out.println(number);
if ((number % 3) == 0) {
System.out.println(number + " is a multiple of 3");
total = total + number;
}
else if ((number % 5) == 0) {
System.out.println(number + " is a multiple of 5");
total = total+number;
}
number++;
}
System.out.println("total = "+ total);
}
}
Looking at how slow I was, I did roughly the same thing as everyone else but swapped to a modulus function. The modulus function gives you the remainder(int) of dividing the first number by the second number, and can be compared to another integer. Here I have used it to check if the current number is directly divisible by 3 or 5, and add it to the total if the value is true.
Try this
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextLong()-1;
System.out.println((n-n%3)*(n/3+1)/2 + (n-n%5)*(n/5+1)/2 - (n-n%15)*(n/15+1)/2);
}
}
}

Categories

Resources