This question already has answers here:
How to sum digits of an integer in java?
(22 answers)
Closed 1 year ago.
Suppose
int n = 5
I want to find out the sum of n number. For example:- if n is given by user as 5 then in number array from 1 to 30 we have sum of n number is 14 and 23. Which is int number = 1+4= 5 and 2+3 = 5 that is number == n.
To reduce double digits i.e., if user put 15 then:-
reduce(int doubleDigit){
return (doubleDigit-1) %9 +1;
So to reduce 15 i.e., 1+5=6
But to calculate the sum of 6, how to find? What I want as a result is that when ans is 6 then the output should be 6, 15 (1+5=6) and 24 (2+4=6) which is sum of two digits is equal to ans in the range between 1 to 30.
So do I need to reverse the reduce function or is their any method to solve.
Small code hint will be very helpful.
There is a semi-tautological function for doing this:
public int sumDigits (int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
Related
I have a question regarding an answer that was given here a while ago.
I came up with the same answer myself in the code attached but I'm trying to understand why do I need to divide the input number by 2 (line 10), and not just let the loop run its course till the value of the input number achieved.
1 import java.util.Scanner;
2 public class numIsPrime {
3 public static void main(String[] args) {
4 Scanner sc = new Scanner(System.in);
5 int i = 2;
6 boolean isPrime = true;
7 System.out.println("Enter a number");
8 int num = sc.nextInt();
9
10 while (i < num ) // (i <= num / 2)
11 {
12 if (num % i == 0)
13 isPrime = false;
14 i++;
15 }
16
17 if (isPrime)
18 System.out.println(num + " is a prime number");
19 else // !isPrime
20 System.out.println(num + " isn't a prime number");
21
22 }
23 }
This is the simplest way to calculate if an integer n is probably a prime:
public static boolean isPrime (int n) {
if (n < 2) return false;
BigInteger bigInt = BigInteger.valueOf(n);
return bigInt.isProbablePrime(100);
}
You can insert this function call in a loop where you can pass a new number every iteration. I am using the implementation of BigInteger provided by Java to do the calculation, rather than writing my own. UNLESS this is a homework and you are required to write your own algorithm, I would use this solution.
This base method can then be used for calculating other types of prime numbers. A complete answer can be found here.
UPDATE:
The int parameter in BigInteger.isProbablePrime(int) is a measure of the uncertainty that the caller is willing to tolerate. The larger the number, the "slower" it executes (but the more certain it is). Also, going back to the original question (already answered in the OP's comments section):
why do I need to divide the input number by 2 (line 10), and not just
let the loop run its course till the value of the input number
achieved.
This is an optimization that will make your evaluation run twice as fast. For example, suppose an evaluation of n integers take 10 minutes to complete, excluding even numbers should take half the time. That's a significant improvement. Although you should not optimize prematurely, these sort of optimizations should be done right from the get go. Basically, we all know that even numbers are not prime, so why evaluate it? You want to evaluate unknowns. In my solution, I only evaluate values greater than 2 because by definition, values less or equal to 2 are not prime. I am merely solving that by definition or by mathematical properties.
As mentioned in the comments, dividing by 2 is a simplest optimization to reduce the number of checks, however, existing code has a few issues (e.g. returning true for 0 and 1 which are NOT prime numbers) and may be further optimized:
break/end the loop as soon as isPrime is set to false
skip even numbers by incrementing by 2
calculate until i * i <= num
If this limit is reached, it means that no factor i of num has been found in the range [2, num/i], therefore by definition of the prime numbers, all the remaining numbers in the range [num/i, num] are neither the factors of num, and therefore num is prime.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();
boolean isPrime = num > 1 && (num % 2 != 0 || num == 2);
int i = 3;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += 2; // skip even numbers
}
if (isPrime)
System.out.println(num + " is a prime number");
else
System.out.println(num + " isn't a prime number");
More optimizations are possible if the divisibles of 3 (except 3) are excluded similar to the exclusion of even numbers, then the search continues from 5 and the candidates for primality comply with 6n ± 1 rule (e.g., 5 = 6 - 1, 7 = 6 + 1, 11 = 12 - 1, 13 = 12 + 1, etc.):
boolean isPrime = num > 1 && (num % 2 != 0 || num == 2) && (num % 3 != 0 || num == 3);
int i = 5;
int d = 2;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += d; // check only non-even numbers
d = 6 - d; // switch 2 to 4 and back to 2
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm writing a code that determines the smallest integer that is a sequence of sevens followed by some number of zeros (possibly none) that is divisible by int n. Since this number can be massive, the return value should be a BigInteger.
My code so far has an if-else ladder that covers the case that if any int n is not divisible by two or five is guaranteed to only contain sevens (no zeros). In the case where int n is not divisible by two or five, my thought process was to continue adding sevens to a LinkedList in a while loop, until that list (converted to a BigInteger) is divisible by int n. The same logic goes for the case where int n is divisible by two or five, except a two for-loops would add seven and zero to the list.
My code is getting a runtime error when converting the list to a string and then to a BigInteger, specifically on the line BigInteger numBig = new BigInteger(str);. The error is: "java.lang.NumberFormatException: Zero length BigInteger (in java.math.BigInteger)" Also, I'm not quite sure the logic is sound for the case where int n is divisible by two or five.
You don't need BigInteger for this task. The idea is the following:
First you determine the number of required zeros. Since number composed of only sevens cannot be divided by 2 or 5, the number of zeros is equal to the maximum power of 2 or 5 in number n.
Now we have a number n which is not divisible by 2 or 5. Suppose that a remainder of the division of a number composed of m sevens by n is equal to r:
777...m-times..777 mod n = r
Then number composed of (m+1) sevens will have a remainder 10*r + 7, because
777..(m+1)-times...777 = 777...m-times...7 * 10 + 7
So you can just recalculate the remainder until it becomes zero.
public static BigInteger method(int n) {
int two;
for (two = 0; n % 2 == 0; two++) n /= 2;
int five;
for (five = 0; n % 5 == 0; five++) n /= 5;
int zeros = Math.max(two, five);
int sevens = 1;
int r = 7 % n;
while (r != 0) {
r = (r * 10 + 7) % n;
sevens++;
}
// Now just make a number of 'sevens' sevens and 'zeros' zeros:
StringBuilder result = new StringBuilder();
for (int i = 0; i < sevens; i++) {
result.append("7");
}
for (int i = 0; i < zeros; i++) {
result.append("0");
}
return new BigInteger(result.toString());
}
"Zero length BigInteger" means you're trying to create a BigInteger from something that has length of 0. The stack trace would tell you on which line exactly.
I would guess the bug is in your convert method. If you pass in an empty list, it tries to convert an empty string into BigInteger with new BigInteger("")
I don't know what your algorithm is supposed to do in this case. If for example you want to convert an empty list into the number zero, you can do:
if (res.isEmpty()) return BigInteger.ZERO;
I need something that can calculate the nearest highest multiple of 9. So for example, if I input 1 into this function it will return 9, if I input 10 into this function it will return 18 and so on.
I've tried this 9*(Math.round(number/9)) and 9*(Math.ceil(Math.abs(number/9))) but they return the nearest multiple of 9, so if you input 10 into this function it will return 9, for my purposes it will need to return 18. (There's probably a better way to say this other then "nearest highest")
If anyone can help me that will be great!
You can use this formula.
number + (9 - (number % 9))
And for the exceptional case when the number is a multiple of 9, use a condition:
int result = number % 9 == 0 ? number : number + (9 - (number % 9));
Just add one (max) 9 times and check if it is a multiple of 9 like so:
int x = 9;
int result = 0;
for (int i = x; i < 9; i++)
{
if (i % 9 == 0)
{
result = i;
break;
}
}
// result will contains the 'nearest' 'highest' or it self multiple of 9
You can try defining a multiplier whose value depends on whether number is multiple of 9 or not. Check below code:
int number = 10;
Double ceilValue = Math.ceil(number/9);
double multiplier = 0.0;
if (number % 9 == 0) {
multiplier = ceilValue;
} else {
multiplier = ceilValue + 1;
}
Double result = 9 * multiplier;
System.out.println(result);
Output:18.0
This question already has answers here:
Separating the Digits in an Integer - exercise from Deitel's Java book
(11 answers)
Closed 7 years ago.
Let's say you have an integer '75'. Normally, in your head, you can add the '7' with the '5' in order to get '12'. So you split the number '75' into two different numbers 7 and 5 then add them together. That leads to my question, how can you perform that in java? Is there a Math method that does it for you?
You can use plain maths
int i = 75;
int a = i / 10; // 7
int b = i % 10; // 5
int c = a + b; // 12
You can use some code like:
int num=75;
int sum_digits=0;
while(num>0){
int digit = num%10;
num /= 10;
sum_digits += digit;
}
From Java Malik textbook- determine if an number is divisible by 11..
Code Solution provided:
import java.util.*;
public class Divby11
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int num, temp, sum;
char sign;
System.out.print("Enter a positive integer: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
sign = '+';
do
{
switch (sign)
{
case '+' :
sum = sum + num % 10;
sign = '-';
break;
case '-' :
sum = sum - num % 10;
sign = '+';
}
num = num / 10; //remove the last digit
}
while (num > 0);
if (sum % 11 == 0)
System.out.println(temp + " is divisible by 11");
else
System.out.println(temp + " is not divisible by 11");
}
Why go through all the effort above and just say...
if (sum % 11 == 0)
System.out.println(temp + " is divisible by 11");
else
System.out.println(temp + " is not divisible by 11");
Can any of you experts see why the author would do it this way (long way)?
for the Divisibility Rule of 11:
form the alternating sum of the digits
if this sum is divisible for 11 then the number is divisible for 11
Examples
68090 = 0 - 9 + 0 - 8 + 6 = -11 => TRUE
493827 = 7 - 2 + 8 - 3 + 9 - 4 = 15 = 4 => FALSE
This code example isn't actually dividing by eleven. If you see, it's alternating between adding and subtracting each digit, then checks at the very end if the result is divisible by 11.
For example, look at the following number and how this algorithm works with it:
Start with sum=0, sign='+', num=517
First iteration: sum=7, sign='-', num=51
Second iteration: sum=6, sign='+', num=5
Final iteration: sum=11, sign='-', num=0
The final result is divisible by eleven.
EDIT: The algorithm does indeed look to be implementing the divisibility rule for 11 as dfa mentions in his answer.
You will have to provide more context from the book as to what the author was trying to demonstrate. This code example does not check to see if the number entered is divisible by 11. What it does is it adds every other digit, subtracts every other digit and then checks THAT number to see if it's divisible by 10.
EX
Entered number is 4938
It takes the 8 adds it to sum
Divides by ten giving 493
Takes the 3 subtracts it from sum: sum = 5
Divides by ten giving 49
Takes 9 and adds it to sum: sum = 14
Divides by ten giving 4
Takes 4 subtracts it from sum: sum = 10
THEN it checks if this is divisible by 11.
Ok, I know why now. He/she's trying to teach you something besides computing about numbers
I suspect it is simulating the manual test that digits in the odd positions and the digits in the even positions differ by a factor of 11. In practice using %11 would be the way to go.
EDIT: If the example were truly trying to avoid doing % 11, it should send the sum through again until it is 0.
It an example to show how to implement that particular check. Using your example would not demonstrate the same code methodologies.