I want my program to get all the even digits from a number input. Then multiply those with digits with 2. If the result is a two digit number, add them. At the end i want it to give me the sum of all the even digits.
public class evenplaceadd {
public static void main(String[] args) {
System.out.println(sumOfevenPlace(5566));
}
public static int sumOfevenPlace(int number)
{
int maxDigitLength = 4;
int sum = 0;
for (int i = 0; i < maxDigitLength; i++)
{
if (i % 2 == 0)
{
int digita = number % 10;
int digitb =digita*2;
int digitc;
if(digita < 9)
{
sum = sum + digitb;
}
else if(digitb>9)
{
digitc =(digitb % 10)+ (digitb /10);
sum =sum + digitc;
}
}
else
{
number = number/10;
}
}
return sum;
}
}
Your code seems ok for the most part. There are some minor flaws in the code which I am sure you will be able to figure out after understanding the code provided below. I have changed it up a bit and made it easier to read. Please confirm it is working, and next time please provide the code when asking question. I know you are new to the community, and so am I. Its a learning experience for all of us. All the best in the future :)
public static void int sumOfEvenDigits(int num){
int sum = 0;
int lastDig = 0;
while(num/10 != 0)
{
lastDig = num % 10;
num = num / 10;
if(lastDig % 2 != 0)
{
continue;
}
if(lastDig > 10)
{
sum += lastDig / 10;
sum += lastDig % 10;
}
else
{
sum += lastDig;
}
}
return sum;
}
Related
I want to ask about what mistake I had make because i want to sum up the value in the odd position into Sumlast variable and the sum of even position value into Sumlastwo variable.
However I am required to double up the every value in even position then separate them into 2 digit like 9X2 = 18 ---> 1+8
For the odd value have no issue but when it reach the even position there is some issue.
Example I had did the input : 81
Output:
7
1
But when I type more digit like :9181
it become output:
27
2
it suppose to be (9X2) , (8X2) --> 18 , 16 = 1+8+1+6 = 16
output:
16
2
public static void main(String[] args) {
int c = 1;
int Sumlast = 0;
int Sumlasttwo = 0;
int numeven = 0;
Scanner myscanner = new Scanner(System.in);
System.out.print("Please enter your 8 digit number credit card: ");
String num = myscanner.nextLine();
if(num.length() != 8) //check the number of digit is 8
{
int test = Integer.parseInt(num);
while(test != 0)
{
if(c%2 == 0) //even
{
numeven = test * 2;
while(numeven > 0)
{
Sumlasttwo += (numeven%10);
numeven /= 10;
}
}
else //odd
{
Sumlast += test%10;
}
test /= 10;
c++;
}
System.out.println(Sumlasttwo);
System.out.println(Sumlast);
}
}
You forgot to take the digit from test in the even-case.
int test = Integer.parseInt(num);
while (test != 0)
{
int digit = test % 10;
if (c % 2 == 0) //even
{
int numeven = digit * 2;
while (numeven > 0)
{
Sumlasttwo += numeven % 10;
numeven /= 10;
}
}
else //odd
{
Sumlast += digit;
}
test /= 10;
c++;
}
Also it is more readable to declare numeven as near to its usage as possible.
Sumlast in java conventionally is written sumLast. Also } else { and ...) { is such a convention, but for instance not in C, and not as holy as camel-case names.
Debugging would have helped.
Using a help method would have made the code better:
boolean even = true;
while (test != 0) {
int digit = test % 10;
if (even) {
sumEven += digitsSum(digit * 2);
} else {
sumOdd += digit;
}
test /= 10;
even = !even;
}
private static void digitSum(int n) {
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
I will get to the point quickly. Basically smith numbers are: Composite number the sum of whose digits is the sum of the digits of its prime factors (excluding 1). (The primes are excluded since they trivially satisfy this condition). One example of a Smith number is the beast number 666=2·3·3·37, since 6+6+6=2+3+3+(3+7)=18.
what i've tried:
In a for loop first i get the sum of the current number's(i) digits
In same loop i try to get the sum of the number's prime factors digits.
I've made another method to check if current number that is going to proccessed in for loop is prime or not,if its prime it will be excluded
But my code is seems to not working can you guys help out?
public static void main(String[] args) {
smithInrange(1, 50);
}
public static void smithInrange(int start_val, int end_val) {
for (int i = start_val; i < end_val; i++) {
if(!isPrime(i)) { //since we banned prime numbers from this process i don't include them
int for_digit_sum = i, digit = 0, digit_sum = 0, for_factor_purpose = i, smith_sum = 0;
int first = 0, second = 0, last = 0;
// System.out.println("current number is" + i);
while (for_digit_sum > 0) { // in this while loop i get the sum of current number's digits
digit = for_digit_sum % 10;
digit_sum += digit;
for_digit_sum /= 10;
}
// System.out.println("digit sum is"+digit_sum);
while (for_factor_purpose % 2 == 0) { // i divide the current number to 2 until it became an odd number
first += 2;
for_factor_purpose /= 2;
}
// System.out.println("the first sum is " + first);
for (int j = 3; j < Math.sqrt(for_factor_purpose); j += 2) {
while (for_factor_purpose % j == 0) { // this while loop is for getting the digit sum of every prime
// factor that j has
int inner_digit = 0, inner_temp = j, inner_digit_sum = 0;
while (inner_temp > 0) {
inner_digit = inner_temp % 10;
second += inner_digit;
inner_temp /= 10;
}
// System.out.println("the second sum is " + second);
for_factor_purpose /= j;
}
}
int last_temp = for_factor_purpose, last_digit = 0, last_digit_sum = 0;
if (for_factor_purpose > 2) {
while (last_temp > 0) {
last_digit = last_temp % 10;
last += last_digit;
last_temp /= 10;
}
// System.out.println("last is " + last);
}
smith_sum = first + second + last;
// System.out.println("smith num is "+ smith_sum);
// System.out.println(smith_sum);
if (smith_sum == digit_sum) {
System.out.println("the num founded is" + i);
}
}
}
}
public static boolean isPrime(int i) {
int sqrt = (int) Math.sqrt(i) + 1;
for (int k = 2; k < sqrt; k++) {
if (i % k == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
the output is:
the num founded is4
the num founded is9
the num founded is22
the num founded is25
the num founded is27
the num founded is49
how ever the smith number between this range(1 and 50) are:
4, 22 and 27
edit:I_ve found the problem which is :
Math.sqrt(for_factor_purpose) it seems i should add 1 to it to eliminate square numbers. Thanks to you guys i've see sthe solution on other perspectives.
Keep coding!
Main loop for printing Smith numbers.
for (int i = 3; i < 10000; i++) {
if (isSmith(i)) {
System.out.println(i + " is a Smith number.");
}
}
The test method to determine if the supplied number is a Smith number. The list of primes is only increased if the last prime is smaller in magnitude than the number under test.
static boolean isSmith(int v) {
int sum = 0;
int save = v;
int lastPrime = primes.get(primes.size() - 1);
if (lastPrime < v) {
genPrimes(v);
}
outer:
for (int p : primes) {
while (save > 1) {
if (save % p != 0) {
continue outer;
}
sum += sumOfDigits(p);
save /= p;
}
break;
}
return sum == sumOfDigits(v) && !primes.contains(v);
}
Helper method to sum the digits of a number.
static int sumOfDigits(int i) {
return String.valueOf(i).chars().map(c -> c - '0').sum();
}
And the prime generator. It uses the list as it is created to determine if a given
number is a prime.
static List<Integer> primes = new ArrayList<>(List.of(2, 3));
static void genPrimes(int max) {
int next = primes.get(primes.size() - 1);
outer:
while (next <= max) {
next += 2;
for (int p : primes) {
if (next % p == 0) {
continue outer;
}
if (p * p > next) {
break;
}
}
primes.add(next);
}
}
}
I do not want to spoil the answer finding, but just some simpler code snippets,
making everything simpler, and more readable.
public boolean isSmith(int a) {
if (a < 2) return false;
int factor = findDivisor(a);
if (factor == a) return false;
int sum = digitSum(a);
// loop:
a /= factor;
sum -= digitSum(factor);
...
}
boolean isPrime(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return false;
}
}
return true;
}
int findDivisor(int a){
for(int i = 2; i*i <= a; i++) {
if (a % i == 0) {
return i;
}
}
return a;
}
int digitSum(int a) {
if (a < 10) {
return a;
}
int digit = a % 10;
int rest = a / 10;
return digit + digitSum(rest);
}
As you see integer division 23 / 10 == 2, and modulo (remainder) %: 23 % 10 == 3 can simplify things.
Instead of isPrime, finding factor(s) is more logical. In fact the best solution is not using findDivisor, but immediately find all factors
int factorsSum = 0;
int factorsCount = 0;
for(int i = 2; i*i <= a; i++) {
while (a % i == 0) {
factorsSum += digitSum(i);
a /= i;
factorsCount++;
}
}
// The remaining factor >= sqrt(original a) must be a prime.
// (It cannot contain smaller factors.)
factorsSum += digitSum(a);
factorsCount++;
Here is the code. If you need further help, please let me know. The code is pretty self explanatory and a decent bit was taken from your code but if you need me to explain it let me know.
In short, I created methods to check if a number is a smith number and then checked each int in the range.
import java.util.*;
public class MyClass {
public static void main(String args[]) {
System.out.println(smithInRange)
}
public int factor;
public boolean smithInRange(int a, int b){
for (int i=Math.min(a,b);i<=Math.max(a,b);i++) if(isSmith(i)) return true;
return false;
}
public boolean isSmith(int a){
if(a<2) return false;
if(isPrime(a)) return false;
int digits=0;
int factors=0;
String x=a+¨" ";
for(int i=0;i<x.length()-1;i++) digits+= Integer.parseInt(x.substring(i,i+1));
ArrayList<Integer> pF = new ArrayList<Integer>();
pF.add(a);
while(!aIsPrime(pF)){
int num = pF.get(pF.size-1)
pF.remove(pF.size()-1);
pF.add(factor);
pF.add(num/factor)
}
for(int i: pF){
if((factors+"").length()==1)factors+= i;
else{
String ss= i+" ";
int nums=0;
for(int j=0;j<ss.length()-1;j++){
nums+=Integer.parseInt(ss.substring(j,j+1));
}
}
}
return (factors==digits);
}
public boolean isPrime(int a){
for(int i=2;i<=(int)Math.sqrt(a),i++){
String s = (double)a/(double)i+"";
if(s.substring(s.length()-2).equals(".0")){
return false;
factor = i;
}
}
return true;
}
public boolean aIsPrime(ArrayList<int> a){
for(int i: a) if (!isPrime(a)) return false;
return true;
}
}
In our directions, we have to get a 16 digit number, then sum all the digits in the odd place from right to left. After that, we have to sum all the even place digits from right to left, double the sum, then take module 9. When I try to run my code, I keep getting "Invalid", even if it is with a valid credit card number.
public static boolean validateCreditCard(long number) {
double cardSum = 0;
for (int i = 0; i < 16; i++) {
long cardnumber = (long) Math.pow(10, i);
double oddPlaceSum = 0;
double evenPlaceSum = 0;
if (i % 2 != 0) {
oddPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i))));
} else { // so if i%2 ==0
evenPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i)) * 2 % 9));
}
cardSum += evenPlaceSum + oddPlaceSum;
}
if (cardSum % 10 == 0) {
return true;
System.out.println("Valid");
} else {
return false;
System.out.println("Invalid");
}
}
Try this instead :
Convert the 16 digit number into a String using Long.toString(number).
Iterate through the String character by character and keep track of even and odd indexes.
Convert each char to an Integer using Integer.valueOf() thereby adding them incrementally.
Voila, you got your evenSum and oddSum. Next steps should be trivial.
public static boolean validateCreditCard(long number){
String x = Long.toString(number);
int evenSum = 0;
int oddSum = 0;
for(int i=0; i<x.length; i=i+2) {
oddSum += Integer.valueOf(s[i]);
evenSum += Integer.valueOf(s[i+1]);
}
//Do the next steps with odd and even sums.
Also, do handle IndexOutOfBoundsException as appropriate.
You can do it in a single while loop as digits are fixed, like this:
int digit,evensum,oddsum;
int i=16;
while(i > 0){
digit=number%10;
if(i%2 == 0)
evensum+=digit;
else
oddsum+=digit;
i--;
digit/=10;
}
Try this instead
using Recusion find sum of even placed of digit and sum of odd placed of digit.
class Recursion {
static int count = 0;
static int even =0;
static int odd =0;
public static int Digits(int num) {
if (num > 0) {
count++;
if(count%2 == 0){
even += num%10;
}
else{
odd += num%10;
}
Digits(num / 10);
}
return even;
// for odd
// return odd;
}
public static void main(String[] args) {
int num = 31593;
int res = Digits(num);
System.out.println("Total digits are: " + res);
}
}
Help me How to print both even and odd sum together?
import java.util.Scanner;
import java.io.*;
class factorial {
void fact(int a) {
int i;
int ar[] = new int[10000];
int fact = 1, count = 0;
for (i = 1; i <= a; i++) {
fact = fact * i;
}
String str1 = Integer.toString(fact);
int len = str1.length();
i = 0;
do {
ar[i] = fact % 10;
fact /= 10;
i++;
} while (fact != 0);
for (i = 0; i < len; i++) {
if (ar[i] == 0) {
count = count + 1;
}
}
System.out.println(count);
}
public static void main(String...ab) {
int a;
Scanner input = new Scanner(System.in);
a = input.nextInt();
factorial ob = new factorial();
ob.fact(a);
}
}
This code is work up to a = 10 but after enter number larger then a = 16 it gives wrong answer.
Please help.
As I am not able to post this question if I dont add more info for this question but I assume that the info I provide above is enough to under stand what I want.
Like many of these mathematical puzzles, you are expected to simplify the problem to make it practical. You need to find how many powers of ten in a factorial, not calculate a factorial and then find the number of trailing zeros.
The simplest solution is to count the number of powers of five. The reason you only need to count powers of five is that there is plenty of even numbers in between then to make a 10. For example, 5! has one 0, 10! has 2, 15! has three, 20! has four, and 25! has not five but six as 25 = 5 * 5.
In short you only need calculate the number of powers of five between 1 and N.
// floor(N/5) + floor(N/25) + floor(N/125) + floor(N/625) ...
public static long powersOfTenForFactorial(long n) {
long sum = 0;
while (n >= 5) {
n /= 5;
sum += n;
}
return sum;
}
Note: This will calculate the trailing zeros of Long.MAX_VALUE! in a faction of a second, whereas trying this with BigInteger wouldn't fit, no matter how much memory you had.
Please Note, this is not the mathematical solution as others suggested, this is just a refactoring of what he had initially...
Here I just used BigInteger in place of Int, and simplified your code abit. Your solution is still not optimal. I thought I would just show you what a refactored version of what you posted may look like. Also there was a bug in your initial function. It returned the number of zeros in the whole number instead of just the number of trailing zeros.
import java.math.BigInteger;
import java.util.Scanner;
class factorial {
public static void main(String... ab) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
fact(a);
}
private static void fact(int a) {
BigInteger fact = BigInteger.ONE;
int i, count = 0;
for (i = 1; i <= a; i++) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
String str1 = fact.toString();
for(int j = str1.length() - 1; j > -1; j--) {
if(Character.digit(str1.charAt(j), 10) != 0) {
System.out.println(count);
break;
} else {
count++;
}
}
}
}
Without using factorial
public class TrailingZero {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(trailingZeroes(9247));
}
public static int trailingZeroes(int a) {
int countTwo = 0;
int countFive = 0;
for (int i = a; i > 1; i--) {
int local = i;
while (local > 1) {
if (local % 2 != 0) {
break;
}
local = local / 2;
countTwo++;
}
while (local > 1) {
if (local % 5 != 0) {
break;
} else {
local = local / 5;
countFive++;
}
}
}
return Math.min(countTwo, countFive);
}}
I am a beginner java and trying to solve tricky problem
input=777
output should be 3
7+7+7=21 , 2+1=3;
From the above code if my input is 333 I am getting 9 as answer but when the sum is two digits(777=21) i am getting blank!
public static void main(String[] args)
{
int y=333;//if y is 777 i am getting blank
int sum=0;
String s;
char []ch;
do
{
s=String.valueOf(y);
ch=s.toCharArray();
if(ch.length>1)
{
for(int i=0;i<ch.length;i++)
{
sum+=Character.getNumericValue(ch[i]);
}
}
else
{
System.out.println(sum);
}
y=sum;
}while(ch.length>1);
}
your code maybe loop forever
the right solution is the following below
public static void main(String[] args) throws ParseException {
int y = 777;// if y is 777 i am getting blank
int sum = 0;
String s;
char[] ch;
do {
sum = 0;
s = String.valueOf(y);
ch = s.toCharArray();
if (ch.length > 1) {
for (int i = 0; i < ch.length; i++) {
sum += Character.getNumericValue(ch[i]);
}
} else {
System.out.println(ch[0]);
break;
}
y = sum;
} while (ch.length > 1);
}
Maybe the better choice is the following code
public static void main(String[] args) throws ParseException {
int y = 333;// if y is 777 i am getting blank
int sum = 0;
while (y % 10 != 0) {
sum += y %10;
y = y / 10;
if (0 == y && sum >= 10) {
y = sum;
sum = 0;
}
}
System.out.println(sum);
}
hope that helped
For a task like this, it is best practise to use recursion.
The workflow in pseudocode would look like this:
procedure sumTillOneDigit(n)
split n into it's digits
s := sum of all digits of n
if s has more than one digit:
sumTillOneDigit(s)
else
output s
I am intentionally writing this in pseudocode, since this should help you solving the task. I will not give you a Java implementation, as it looks like a homework to me.
For more information see:
https://en.wikipedia.org/wiki/Recursion_(computer_science)
http://introcs.cs.princeton.edu/java/23recursion/
You are getting that because you put the print statement in else condition..
Also note that to reset your sum value before reusing it. I.e. Set sum=0 at the start of do loop.
EDIT : there are two solutions to print you value
1. Don't put you print statements inside else conditions
Print sum outside the do while loop
First of all you must reset the value of sum variable.
and secondly you must print s in else condition and not the sum and rest is fine.
public static void main(String[] args)
{
int y=333;//if y is 777 i am getting blank
int sum;
String s;
char []ch;
do
{
sum=0;
s=String.valueOf(y);
ch=s.toCharArray();
if(ch.length>1)
{
for(int i=0;i<ch.length;i++)
{
sum+=Character.getNumericValue(ch[i]);
}
}
else
{
System.out.println(s);
}
y=sum;
}while(ch.length>1);
}
I think your solution has wrong basics. There is no point to convert your number to String and handle this as char array. You are doing too much unnecessary operations.
You can do is simpler if you stick with numbers.
You can do it using recursion:
public static int sumRec(int number){
if (number<10){
return number;
}
int sum = 0;
while(number!=0){
sum += number %10;
number /= 10;
}
return sumRec(sum);
}
or itteration
public static int sumIt(int number){
while(number>=10){
int sum = 0;
while(number!=0){
sum += number %10;
number /= 10;
}
number = sum;
}
return number;
}
it is much simpler, right?
You can solve this by 1 line:
public static int sumDigits(int n) {
return (1 + ((n-1) % 9);
}
For example: input 777--> return 1 + ( (777-1) % 9) = 3
Also can work with negative number.
Recursive variant
public static int myFunction(int num){
if(num/10 == 0){
return num;
}
int digitSum = num%10 + myFunction(num/10);
if(digitSum/10 == 0){
return digitSum;
}
return myFunction(digitSum);
}
public static int sum_of_digits(int n) {
return --n % 9 + 1;
}