I am trying to sum every other digit in the card number by doing this:
/*
Return the sum of the odd-place digits.
*/
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 1; i <= maxDigitLength; i++)
{
if (i % 2 == 1)
{
sum = sum + (int)(number % 10);
}
break;
}
return sum;
}
All I get is 6. The sum I am looking for is supposed to be 37.
You're breaking out of the loop on the very first iteration only. So, you won't go past to another iteration.
However, removing the break too won't solve your problem. number % 10 will always give you the last digit of the number, and not every alternate number. You should follow this approach:
num % 10 - Will give you last digit.
Then update the num by trimming off the last 2 digits.
Repeat
Try this ... this should work for you
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 0; i < maxDigitLength; i++)
{
if (i % 2 != 0)
{
sum = (sum + (int)(number % 10));
number = number/10;
}else {
number = number/10;
}
}
return sum;
}
What I have done here is if i is odd, I take a mod of the number so I get the last digit of the number and then add it to sum and then I get rid of the last digit by dividing it with 10 and if the number is even I just get rid of the digit in the ith position.
Here I am collecting the digits in odd places in reverse order.
I haven't seen the minimum solution yet, so here goes:
public static int sumOddDigits(long input) {
int sum = 0;
for (long temp = input; temp > 0; temp /= 100) {
sum += temp % 10;
}
return sum;
}
You don't need to divide by 10 and check if it's an even number, you can just divide by 100 every time.
Demo: http://ideone.com/sDZfpU
Here is updated code in which i have removed logic of flag.This is shorter and easier to understand.
public static int sumOfOddDigits(long number){
int sum = 0;
String newString = new StringBuilder(String.valueOf(number)).reverse().toString();
number = Long.parseLong(newString);
while (number != 0){
sum = (int) (sum + number % 10);
number = number / 100;
}
return sum;
}
Related
I am having trouble to add a set of integers in a sequence. I have three variable: start, number, and end.
If I "start" at 5, then add all the integers up to "number" ( for example 9) , then decrement from 9 to the integer "end" (in this case to -1): (5,9,-1) => 5+6+7+8+9+8+7+6+5+4+3+2+1+0+ - 1 , which then i would print the result: total = 70. how can i accomplish this?
public class SequenceNumbers {
public static void main(String[] args) {
int start = 5;
int num = 9;
int end = -1;
int sum = 0;
for(int i = start; i <= num; i++)
{
// sum = sum + i;
sum += i;
}
int total = 0;
for ( int n = num; n != end; n--) {
total = (sum + (num - 1));
}
System.out.println("Result = " + total);
}
}
In the second loop, you overwrite total in each iteration. I'd keep the same pattern you had in the first loop, and just keep adding to sum. Note that it should start with num - 1, though, so you don't count that number twice:
int sum = 0;
for(int i = start; i <= num; i++) {
sum += i;
}
for ( int i = num - 1; i >= end; i--) {
sum += i;
}
System.out.println("Result = " + sum);
I guess you need this for an exercise?
But if you need a one-liner, this is a possible solution:
import java.util.*;
import java.util.stream.*;
public class MyClass {
public static void main(String args[]) {
;
int start = 5;
int num = 9;
int end = -1;
int total = Stream.concat(Stream.iterate(start, n -> n + 1).limit(num-start+1), Stream.iterate(num-1, n -> n - 1).limit(num-end)).mapToInt(Integer::intValue).sum();
System.out.println("Result = " + total);
}
}
You were almost there. All your code is fine until this one line in your second for loop:
total = (sum + (num - 1));
This line says "set total equal to sum plus one less than num". There's a problem there; sum and num are never changed by the for loop, so actually your for loop is doing nothing. You've set up your for loop nicely, though, and you gave yourself the variable n. All you need to do is keep adding to sum, and add n each time, like so:
sum += n;
Then in your println you can just use sum instead of total, like so:
System.out.println("Result = " + sum);
On second iteration for the total result you should decrement from max number which is 9 to min number which is -1. That means greater or equal to lowest value. ; >= ; -- .
The != comparison operator is to compare two values and the result is always a boolean type.
I have this code that takes a digit and returns a value of the digit that is in that digit position in the sqrt(2):
public static int sqrtTwo(int digit)
{
//1.41421356237…
double result = Math.sqrt(2.0);
String resultString = String.valueOf(result);
if (digit == 0) {
return Integer.parseInt(resultString.substring(0, 1));
}
if (digit + 1 >= resultString.length()) {
digit = resultString.length() - 2;
}
return Integer.parseInt(resultString.substring(digit + 1, digit + 2));
}
But I can only get so many digits by using it. The Math class would return a double which is limited. I want to calculate a sqrt value up to a certain digit, be it a 100th or 500th digit, no matter. How should I do that?
I have found this code, but it looks limited by double as well:
static double squareRoot(int number, int precision)
{
int start = 0, end = number;
int mid;
// variable to store the answer
double ans = 0.0;
// for computing integral part
// of square root of number
while (start <= end)
{
mid = (start + end) / 2;
if (mid * mid == number)
{
ans = mid;
break;
}
// incrementing start if integral
// part lies on right side of the mid
if (mid * mid < number) {
start = mid + 1;
ans = mid;
}
// decrementing end if integral part
// lies on the left side of the mid
else {
end = mid - 1;
}
}
// For computing the fractional part
// of square root upto given precision
double increment = 0.1;
for (int i = 0; i < precision; i++) {
while (ans * ans <= number) {
ans += increment;
}
// loop terminates when ans * ans > number
ans = ans - increment;
increment = increment / 10;
}
return ans;
}
the "2" in the big decimal constructor is the value of what operation you want to do, the 1000 in the MathContext is how many digits you want to get from it.
so like this is how I would get get sqrt(2) to 1000 decimal places
public static void main(String[] args) {
BigDecimal digits = new BigDecimal("2");
BigDecimal num = digits.sqrt(new MathContext(1000));
System.out.println(num.toString());
}
I have a program that is supposed to decrypt a number to its primes. The primes also have an order: for instance, 2 is the 1st prime number, 3 is the second 5 is the third and so on. The indexes are 1 is for a, two is for b, three is for c and so on. I don't know how to compare the two array lists in order to assign an index to each prime so I can decode a word which is encrypted in the number 72216017. The number 72216017 has the primes 17,19,47,67,71. If 2,3,5,7,11... are a,b,c,d,e... these five prime numbers make up the word ghost, I just don't know how to assign and sort these numbers by their index.
package name;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PrimeFactorsEffective {
private static int z;
private int w = z;
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
if (n > 1) {
factors.add(n);
System.out.println(factors);
z = Collections.max(factors);
}
}
return factors;
}
public static void main(String[] args) {
System.out.println("Primefactors of 72216017");
for (Integer integer : primeFactors(72216017)) {
System.out.println(integer);
}
List<Integer> factors1 = new ArrayList<Integer>();
List<String> index1 = new ArrayList<String>();
int i;
int element = 0;
int num = 0;
int maxCheck = z; // maxCheck limit till which you want to find prime numbers
boolean isPrime = true;
String primeNumbersFound = "";
//Start loop 1 to maxCheck
for (i = 1; i <= maxCheck; i++) {
isPrime = CheckPrime(i);
if (isPrime) {
primeNumbersFound = primeNumbersFound + i + " ";
factors1.add(i);
factors1.get(num);
}
}
System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
System.out.println(factors1);
}
public static boolean CheckPrime(int numberToCheck) {
int remainder;
for (int i = 2; i <= numberToCheck / 2; i++) {
remainder = numberToCheck % i;
if (remainder == 0) {
return false;
}
}
return true;
}
}
You can store the primes in a List (primes in this list will be in increasing order). Now you can use Collections.BinarySearch to get the index of the prime for which you wan to find the corresponding alphabet. Once you got the index (index here according to you starts from 1, so a's index is 1, b's index is 2, c's index is 3 and so on) you can do simply something like char currentCharacter = (char) ('a' + primeIndex - 1) and the variable currentCharacter will store the alphabet corresponding to primeIndex.
Some other minor things that I'd like to suggest:
Which checking whether a number is prime or not, you can simply check upto square-root of numberToCheck. So you can replace your loop for (int i = 2; i <= numberToCheck / 2; i++) to for (int i = 2; i*i <= numberToCheck; i++). Note that It is not a good idea to calculate square-root using Math.sqrt, instead you can have a condition like i*i <= numberToCheck.
Please refrain from naming your packages that seem to be random.
As of Java SE 7 explicit type-arguments while initializing the list are not required. You can replace List<Integer> factors1 = new ArrayList<Integer>() with List<Integer> factors1 = new ArrayList<>(). Please read this for more information.
Your factor method don't really look good to me, it don't give correct results. Please see the following method that gives correct result:
{{
public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<>();
for (int i = 2; n>1; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
z = Collections.max(factors);
return factors;
}
I have an int that ranges from 0-99. I need to get two separate ints, each containing one of the digits. I can't figure out how to get the second digit. (from 64 how to get the 6) This is my code:
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
//????
}
}
return n;
}
You can do integer division by 10. For example, in the following code res should equal 4:
int res = 42 / 10;
Simply divide by 10.
...
if(index) {
n = pos/10;
}
...
Simple: in order to get any leading digit; just create a loop; and during each run, divide by 10.
In your case, you can even omit the loop ;-)
you can do:
if(index){
return x % 10;
}
return x / 10;
or maybe a little something
public int getNumber(....){
return index ? x % 10 : x / 10;
}
Just divide the number by 10. If it's int, the result will be int.
class Main {
public static void main(String[] args) {
int a = 8;
int b = 28;
int c = 99;
System.out.println(a / 10);
System.out.println(b / 10);
System.out.println(c / 10);
}
}
Here is a trick. Replace your //???? with below code.
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
Complete code should look like,
public int getNumber(int pos, boolean index){//if index = 1 - first digit, if index = 0 - second digit
int n;
if(index){
n = pos%10;
}else{
if(pos<10){
n=0;
}else{
Integer posInt= new Integer(pos);
n=Integer.parseInt( posInt.toString().substring(0, 1));
}
}
return n;
}
Scanner scan = new Scanner(System.in);
System.out.println("Give a number");
int n = scan.nextInt();
int secondNumber = 0;
while (n > 9) {
secondNumber= n % 10;
n /= 10;
}
to find the first number you need to add to while a constant = n/10; (firstNumber = n / 10;)
How can I make the following allow negative numbers and treats them as positives. Ex. -91 = 10
It currently works for taking int n and adding all digits, but just for positives. Thanks!
public static int sumOfDigits(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n = n / 10;
}
return sum;
}
Simple solution: add n = Math.abs(n) as the first line of the function. This solution works for all numbers, except Integer.MIN_VALUE.
Always correct solution: replace loop condition by n != 0 and return Math.abs(sum) as the result.
public static int sumOfDigits(int n) {
if (n == 0) return 0;
else return (n % 10) + sumOfDigits(n / 10);
}