If - else doesn't work - where could be mistake - java

world! :)
It is my third programming day (please, be lenient...)
Code was intended to find out whether the sum (when it reaches 1 digit only) of digits of number 123456789 can be divided by 9.
I cannot find how to make second 'else' work - any help and explanation why so would be highly appreciated:
package lesson3;
public class Task6 {
public static void main(String[] args) {
int n=123456789;
System.out.println(n);
do{
private static int sumDigits(int n)
int s=sumDigits(n);
if (s < 10) ;
{
if (s == 9) System.out.println("divides by 9");
else System.out.println("doesn't divide by 9");
break;
}
else n = s;
}while (true);
}

The function, sumDigits should return the sum of digits of the parameter, n. For this, you can add each digit of n to a variable, sum initialized with the value, 0. The value of x % 10 gives you the last digit of x. Every time you add the last digit of n to sum, divide it by 10 to make it one digit less from the end.
You need a loop to pass the sum of digits to sumDigits until the sum of digits become a single digit. I suggest you use a do-while loop which guarantees its body to be executed at least once.
At the end of the loop mentioned in point#2, you will have the sum of digits as a single digit. The final thing that you need to do now is to check if this sum is divisible by 9.
Note that if x % y == 0, then x is divisible by y.
Demo:
public class Main {
public static void main(String[] args) {
int n = 123456789;
int singleDigitSum = 0;
int divisibleBy = 9;
do {
singleDigitSum = sumDigits(n);
n = singleDigitSum;
} while (singleDigitSum > 9);
if (singleDigitSum % divisibleBy == 0) {
System.out.println("The single digit sum is divisible by " + divisibleBy);
} else {
System.out.println("The single digit sum is divisible by " + divisibleBy);
}
}
private static int sumDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}
Output:
The single digit sum is divisible by 9
Note: Java does not allow defining a method/function inside another method/function. You have done this mistake by defining the function, sumDigits inside the method, main.

Try the code below:
package lesson3;
public class Task6 {
public static void main(String[] args) {
int number = 123456789;
int sumOfDigits = sumDigits(number);
if (sumOfDigits%9 == 0) {
System.out.println("divides by 9");
return;
}
System.out.println("doesn't divide by 9");
}
public static int sumDigits(int num)
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
return sum;
}

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
}
}

Java - How to check if a 13 digit isbn number is valid

I need to write a program that allows the user to enter a 13-digit ISBN as a single integer.
The program should then determine and show whether the number is valid according to the formula above. It also needs to print an error message if the user tries to enter a number longer than 13 digits.
Below is the code I am working on.
I'm new to java and I don't understand where it went wrong. I also don't seem to figure out how to get the length of a long variable.
import java.util.Scanner;
public class ISBNChecker{
public static void main(String [] args){
long isbnNumber;
long isbnTotal;
long x;
Scanner scnr = new Scanner(System.in);
isbnNumber = scnr.nextLong();
while (isbnNumber > 0) {
x = isbnNumber % 10;
isbnTotal = total + x;
isbnNumber = isbnNumber / 10;
x = isbnNumber % 10;
isbnTotal = total + (3 * x);
isbnNumber = isbnNumber / 10;
}
if (isbnTotal % 10 = 0) {
System.out.println("Number is valid!");
}
else {
System.out.println("Number is invalid.");
}
}
}
Fix your (own) current code
In your original code, you have a couple of tiny errors:
isbnTotal = total + x;
total is not declared anywhere, and isbnTotal is not initialized.
if (isbnTotal % 10 = 0) {
You need to compare with double =, a single one is for assignation, double == is for comparison.
Separate your code into modules to improve it
... determine and show whether the number is valid according to the formula above.
I think that you forgot to write the formula, but according to Wikipedia, is this one:
So, you need to check if the sum of all digits multiplied by their weight (alternating 1 and 3) is a multiple of 10.
So, first of all we need to get the sum of all digits and multiply each digit by 1 or 3 alternating (backwards as we're gonna be using the modulo operator).
So, we need something like this:
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
Let me explain what the above code does, is make use of the ternary operator (CTRL-F on the page to read about it), to determine if we need to multiply by 1 or 3, in the formula it starts with 1, so the easiest way to do it is by checking if the current index is even or odd, if even, multiply by 1, otherwise multiply by 3, and adds that number to the sum.
Then it divides the current number by 10.
Then all we have to do is check if the sum of all digits multiplied by their respective weights is a multiple of 10.
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
And just before that, if the given number doesn't have 13 digits, we say that it isn't.
So, in the end our program should be something like:
public class ISBNChecker {
public static void main(String[] args) {
String isbnNumber = "978030640615";
if (isbnNumber.length() != 13) {
System.out.println("ISBN Number is invalid");
return;
}
if (isAValidISBN(Long.parseLong(isbnNumber))) {
System.out.println(isbnNumber + " is a valid ISBN");
} else {
System.out.println(isbnNumber + " is not a valid ISBN");
}
}
private static int getSum(long isbn) {
int count = 0;
int sum = 0;
do {
sum += count % 2 == 0 ? isbn % 10 : 3 * (isbn % 10);
count++;
isbn /= 10;
} while (isbn > 0);
return sum;
}
private static boolean isAValidISBN(long isbn) {
return getSum(isbn) % 10 == 0;
}
}
And if we take the Wikipedia value, we get this output:
9780306406157 is a valid ISBN
I don't understand your question clearly, but I suppose what you want to do is validate if the number provided by the user has 13 digits or not, you could do this:
public static void main(String[] args) {
String userNumber;
Scanner scnr = new Scanner(System.in);
System.out.println("Enter ISBN number, 13 digit");
userNumber = scnr.nextLine();
/*regular expression to verify that it contains only 13 digits*/
if(userNumber.matches("^[0-9]{13}$")) {
System.out.println("Number is valid");
} else {
System.out.println("Number is invalid");
}
}
First of all, what do you mean with:
according to the formula above.
What formula do you mean? And Second, to get the length of an long or integer just do:
int length = ("" + isbnNumber).length()
And btw, when you are doing an if statement do "==" instead of "=".
if (isbnTotal % 10 = 0) {
…should be:
if (isbnTotal % 10 == 0) {
Or better, reverse so compiler would have caught your typo.
if (0 == isbnTotal % 10) {

Problem with else (program jump to else if there is no reason to do that)

So I'm practicing writing simple Java programs. I made one to change binary numbers to decimal. In last loop below all if(){}'s my program jumps to else without reason to do so. I've changed this last else to another if statement and program is running properly. But I wonder HOW it is possible that the first program is jumping to else. What property of if-else statements is making that?
Here is the code and outputs of both programs:
import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
System.out.println("Put binary number: ");
Scanner sn = new Scanner(System.in);
String container = sn.nextLine();
System.out.println(binaryToNumber(container));
}
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
}
if (x==48) { //if digit from binary number is 0, just skip to next power of 2
power++;
}
else {
System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
}
}
return result;
}
}
Output:
Put binary number:
10110105
issue with 8 digit
issue with 6 digit
issue with 4 digit
issue with 3 digit
issue with 1 digit
90.0
#### AND SECOND:
import java.util.Scanner;
public class NumberToBinary1 {
public static void main(String[] args) {
System.out.println("Put binary number: ");
Scanner sn = new Scanner(System.in);
String container = sn.nextLine();
System.out.println(binaryToNumber(container));
}
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
}
if (x==48){ //if digit from binary number is 0, just skip to next power of 2
power++;
}
if(x!=49 && x!=48) {System.out.println("issue with "+(i+1)+" digit"); //if digit from binary number is not 1 or 0 -> give error
}
}
return result;
}
}
Output:
Put binary number:
10110105
issue with 8 digit
90.0
Because in your first program else belongs only to second if statement, that's mean all values that not pass this if will go to else. In your second program you modified your statement. You can also try to modify your first program to this, it should give you the same result:
private static double binaryToNumber(String container) {
int numberLength = container.length();
double result = 0;
double power = 0;
for (int i = numberLength-1; i >= 0; i--) {
char a = container.charAt(i);
int x =a;
if (x == 49) { //if digit from binary number is 1 add 2^(number of power) to result
result += java.lang.Math.pow(2d, power);
power++;
} else if (x==48) { //if digit from binary number is 0, just skip to next power of 2
power++;
} else {
System.out.println("issue with "+(i+1)+ " number"); //else give error with i+1th digit
}
} return result;
}

Represent an Integer as a sum of Consecutive positive integers

I am writing code for counting the number of ways an integer can be represented as a sum of the consecutive integers. For Example
15=(7+8),(1+2+3+4+5),(4+5+6). So the number of ways equals 3 for 15.
Now the input size can be <=10^12. My program is working fine till 10^7(i think so, but not sure as i didnt check it on any online judge. Feel free to check the code for that)
but as soon as the i give it 10^8 or higher integer as input. it throws many runtime exceptions(it doesnt show what runtime error). Thanks in advance.
import java.io.*;
//sum needs to contain atleast 2 elements
public class IntegerRepresentedAsSumOfConsecutivePositiveIntegers
{
public static long count = 0;
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
long num = Long.parseLong(br.readLine()); //Enter a number( <=10^12)
driver(num);
System.out.println("count = " + count);
}
public static void driver(long num)
{
long limit = num / 2;
for(long i = 1 ; i <= limit ; i++)
{
func(i,num);
}
}
public static void func(long i,long num)
{
if(i < num)
{
func(i + 1,num - i);
}
else if(i > num)
{
return;
}
else
{
count++;
}
}
}
Use some math: if arithmetic progression with difference 1 starts with a0 and contains n items, then its sum is
S = (2 * a0 + (n-1))/2 * n = a0 * n + n * (n-1) / 2
note that the second summand rises as quadratic function. So instead of checking all a0 in range S/2, we can check all n is smaller range
nmax = Ceil((-1 + Sqrt(1 + 8 * S)) / 2)
(I used some higher approximation).
Just test whether next expression gives integer positive result
a0 = (S - n * (n - 1) / 2) / n
Recursive function isn't suitable when you have big input size like your case.
The maximum depth of the java call stack is about 8900 calls and sometimes only after 7700 calls stack overflow occurs so it really depends on your program input size.
Try this algorithm I think it worked for your problem:
it will work fine until 10^9 after that it will take much more time to finish running the program.
long sum = 0;
int count = 0;
long size;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number <=10^12: ");
long n = in.nextLong();
if(n % 2 != 0){
size = n / 2 + 1;
}
else{
size = n / 2;
}
for(int i = 1; i <= size; i++){
for(int j = i; j <= size; j++){
sum = sum + j;
if(sum == n){
sum = 0;
count++;
break;
}
else if(sum > n){
sum = 0;
break;
}
}
}
System.out.println(count);
Output:
Enter a number <=10^12: 15
3
Enter a number <=10^12: 1000000000
9
BUILD SUCCESSFUL (total time: 10 seconds)
There's a really excellent proof that the answer can be determined by solving for the unique odd factors (Reference). Essentially, for every odd factor of a target value, there exists either an odd series of numbers of that factor multiplied by its average to produce the target value, or an odd average equal to that factor that can be multiplied by double an even-sized series to reach the target value.
public static int countUniqueOddFactors(long n) {
if (n==1) return 1;
Map<Long, Integer> countFactors=new HashMap<>();
while ((n&1)==0) n>>>=1; // Eliminate even factors
long divisor=3;
long max=(long) Math.sqrt(n);
while (divisor <= max) {
if (n % divisor==0) {
if (countFactors.containsKey(divisor)) {
countFactors.put(divisor, countFactors.get(divisor)+1);
} else {
countFactors.put(divisor, 1);
}
n /= divisor;
} else {
divisor+=2;
}
}
int factors=1;
for (Integer factorCt : countFactors.values()) {
factors*=(factorCt+1);
}
return factors;
}
As #MBo noted, if a number S can be partitioned into n consecutive parts, then S - T(n) must be divisible by n, where T(n) is the n'th triangular number, and so you can count the number of partitions in O(sqrt(S)) time.
// number of integer partitions into (at least 2) consecutive parts
static int numberOfTrapezoidalPartitions(final long sum) {
assert sum > 0: sum;
int n = 2;
int numberOfPartitions = 0;
long triangularNumber = n * (n + 1) / 2;
while (sum - triangularNumber >= 0) {
long difference = sum - triangularNumber;
if (difference == 0 || difference % n == 0)
numberOfPartitions++;
n++;
triangularNumber += n;
}
return numberOfPartitions;
}
A bit more math yields an even simpler way. Wikipedia says:
The politeness of a positive number is defined as the number of ways it can be expressed as the sum of consecutive integers. For every x, the politeness of x equals the number of odd divisors of x that are greater than one.
Also see: OEIS A069283
So a simple solution with lots of room for optimization is:
// number of odd divisors greater than one
static int politeness(long x) {
assert x > 0: x;
int p = 0;
for (int d = 3; d <= x; d += 2)
if (x % d == 0)
p++;
return p;
}

Write a program to round a number to the next multiple of 10 given the following conditions?

Write a program to Round a number to the next multiple of 10 if its ones digit is 5 or more, otherwise round it the previous multiple of 10.So, 25 and 26 round to 30 where as 23 and 24 round to 20. 20 also rounds to 20. You have been given 4 ints as input. Round each of the input values and return their sum.
MyApproach
I created 2 functions in the first function I counted the sum of all 4 numbers.
In the second function I checked the UnitDigtit if>=5 &&<=9 Then proceed with set of statements given in the question.
else
I checked if Its a one digit or two or any digit number.If One digit I returned num=0 else I proceded with the sets of statements.
Sample Input #1
sumRounded(11,15,23,30)
Sample Output #1
80 (11 rounds to 10, 15 to 20, 23 to 20 and 30 to 30)
Sample Input #2
sumRounded(1,3,7,9)
Sample Output #2
20
public int sumRounded(int num1, int num2, int num3, int num4)
{
int a=checkRound(num1);
int b=checkRound(num2);
int c=checkRound(num3);
int d=checkRound(num4);
return a+b+c+d;
}
public int checkRound(int num)
{
int a=num%10;
if((a>=5) &&(a<=9))
{
if(a==5)
{
num=num+5;
}
else if(a==6)
{
num=num+6;
}
else if(a==7)
{
num=num+7;
}
else if(a==8)
{
num=num+8;
}
else if(a==9)
{
num=num+9;
}
return num;
}
else
{
if((num/10)!=0)
{
if(a==1)
{
num=num-1;
}
else if(a==2)
{
num=num-2;
}
else if(a==3)
{
num=num-3;
}
else if(a==4)
{
num=num-4;
}
return num;
}
else
{
return num=0;
}
}
}
Results:
Parameters Actual Output Expected Output
'289' '3' '25' '308' 644 630
Rounding
If the remainder is less than 5, subtract it from num. Otherwise, add ten minus the remainder to the num. Something like,
static int checkRound(int num) {
int rem = num % 10;
return rem < 5 ? num - rem : num + (10 - rem);
}
or use Math.round(float) like
static int checkRound(int num) {
return Math.round((float) num / 10) * 10;
}
Varargs
You could also implement sumRounded as a varargs method with a for-each loop
static int sumRounded(int... nums) {
int sum = 0;
for (int num : nums) {
sum += checkRound(num);
}
return sum;
}
Testing
Then you could test it like,
public static void main(String[] args) {
System.out.println(sumRounded(11, 15, 23, 30)); // == 80
System.out.println(sumRounded(1, 3, 7, 9)); // == 20
}
Simply use the reminder check inside checkRounded method
int number = 23;
int output=0;
if(number%10<5){
output=(number/10)*10;
}
else{
output=((number/10)+1)*10;
}
System.out.println(output);
You simply put following code in you chexkRound method
int a = num % 10;
if ((a >= 5) && (a <= 9)) {
num = 10 * (num / 10 + 1);
} else {
num = 10 * (num / 10);
}
return num;
If you want to fix you way do the following but Exbury's answer is a shorter way of doing it.
If you are rounding up you should add the 10 minus the number, not the number itself. So for example, 26 rounded up should be 26+(10-6) = 26+(4) = 30
Well the following code perfectly suits your need
//code starts
public static void main(String[] args) {
System.out.println("The answer is: " + getSum(2,5,19));
}
public static int getSum(int... nums) {
int sum = 0;
for (int n : nums) {
int lastDigit = n % 10;
if (lastDigit >= 5) {
sum = sum + n + (10 - (lastDigit));
} else {
sum = sum + 10 * (n / 10);
}
}
return sum;
}
//code ends

Categories

Resources