I'm trying to write a class which checks if a number is an Armstrong number or not. I'm having trouble with the following block of code.
public boolean checkNum(long num) {
digits = (int) (Math.log10(num) + 1);
String number = String.valueOf(num);
numDigits = number.toCharArray();
for (int i = 0; i < numDigits.length; i++) {
digit = numDigits[i] * 1.0;
power = digits * 1.0;
sum = sum + (long) (Math.pow(digit, power));
}
if (sum == num) {
return true;
} else {
return false;
}
}
The casting doesn't seem to work, and checkNum returns false every time. Is this a correct method, and are there any better ways of doing this?
Try this, using only arithmetic operations and it works for non-negative integers with an arbitrary number of digits (as long as they fit into a long).
public boolean checkNum(long num) {
long n = num;
long sum = 0;
// find the number of digits
int power = (int) Math.floor(Math.log10(n == 0 ? 1 : n)) + 1;
while (n != 0) {
int digit = (int) n % 10;
sum += Math.pow(digit, power);
n /= 10;
}
return sum == num;
}
Alternatively (albeit less efficiently) you could transform the number into a string and iterate over each of the characters converting them into digits. Here's a fixed version of your intended solution, with comments on the key points:
public boolean checkNum(long num) {
String number = String.valueOf(num);
char[] numDigits = number.toCharArray();
long sum = 0;
// a simple way to obtain the number of digits
int power = numDigits.length;
for (int i = 0; i < numDigits.length; i++) {
// this is how we transform a character into a digit
int digit = Character.digit(numDigits[i], 10);
// we need to rise digit to the value of power
sum = sum + (long) Math.pow(digit, power);
}
if (sum == num) {
return true;
} else {
return false;
}
}
For example, use either implementation to verify that the following are Armstrong numbers:
checkNum(6)
=> true
checkNum(371)
=> true
checkNum(1634)
=> true
You can also use this simple logic
public class Armstrong {
public static void main(String[] args) {
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
Guess This will work:
boolean isArmstrong(int x){
int s=0;
int u=x;
while(x!=0)
{
int y=x%10;
s=s+(y*y*y);
x=x/10;
}
if(u==s)
return true;
else
return false;
}
How to Check Number is Armstrong or Not
public boolean isArmstrongNum(int input)
{
int sum=0,rem,temp;
temp=input;
while(input>0)
{
rem=input%10;
input=input/10;
sum=sum+(rem*rem*rem);
}
return sum==temp;
}
In Kotlin, you can use:
fun main() {
println("---------------------------------------")
val userInputValues = Scanner(System.`in`)
//* Kotlin Program to Display Armstrong Numbers Between Intervals Using Function
println("* Kotlin Program to Display Armstrong Numbers Between Intervals Using Function\n")
println("Enter your number range")
println("Enter start number of your range \t ")
val startRange = userInputValues.nextInt()
println("Enter end number of your range \t ")
val endRange = userInputValues.nextInt()
println("\n\n------ Armstrong number between $startRange and $endRange ------ ")
for (number in startRange..endRange) {
var stringNumber : String = number.toString()
var numberArray = stringNumber.toCharArray()
var powerOfNumber:Int = numberArray.size;
var result = 0
for (digit in numberArray){
var intDigit:Int = digit.toString().toInt()
result += intDigit.toDouble().pow(powerOfNumber.toDouble()).toInt()
}
if(result == number){
println( "$number is Armstrong number")
}
}
println("---------------------------------------")
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the number: ");
int number=scanner.nextInt();
scanner.close();
int lastDigit=0;
int reverseNum=0;
int originalNumber=number;
while(originalNumber!=0) {
lastDigit=originalNumber%10;
reverseNum +=(lastDigit*lastDigit*lastDigit);
originalNumber /=10;
}
if(reverseNum==number) {
System.out.println("Number is Armstrong");
}
else {
System.out.println("Number is not Armstrong");
}
}
This image is testing image of this code in terminal.
The best way is using while loop.
Here is your Answer for finding 3 digits Armstrong numbers.
import java.util.Scanner;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
int rem = 0;
int cu = 0;
int val = 0;
while(num != 0){
rem = num%10;
cu = rem*rem*rem;
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a Armstrong number ");
}else{
System.out.println("No its not a Armstrong number ");
}
}
}
///////////////////////////////////////////
Here I have done a code to find armstrong number dynamically:
import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
if(isArmstrongNumber(input())) {
System.out.println("armstrong number");
} else {
System.out.println("Not armstrong number");
}
}
private static int input() {
try(Scanner reader = new Scanner(System.in)) {
return reader.nextInt();
}
}
private static int digitCount(int num) {
int count = 0;
while(num > 0) {
num = num / 10;
count++;
}
System.out.println("No of digit : " + count);
return count;
}
private static int power(int num, int count) {
int sum = 0;
while(num > 0) {
int result = 1;
int r2 = num % 10;
num /= 10;
for(int digit = count; digit > 0; digit--) {
result *= r2;
}
sum += result;
}
System.out.println("Sum : " + sum);
return sum;
}
public static boolean isArmstrongNumber(int num) {
int count = digitCount(num);
int sum = power(num, count);
return sum == num;
}
}
Here is the result:
371
No of digit : 3
Sum : 371
armstrong number
Hope this code helps you better.
Related
I am trying to do some mock questions of coding for an entrance exam, I came about this question and I am stuck at the PRIME NUMBERS part.
Here is the question:
Consider the below series: 1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17, … This series is a mixture of 2 series – all the odd terms in this series form a Fibonacci series and all the even terms are the prime numbers in ascending order. Write a program to find the Nth term in this series. For example, when N = 14, the 14th term in the series is 17. So only the value 17 should be printed out.
public class OandF {
// main
public static void main(String[] args) {
System.out.println(dofibo(9));
}
public static int dofibo(int m) {
if(m == 0) {
return 0;
}
if(m == 1) {
return 1;
}
return dofibo(m-1) + dofibo(m-2);
}
}
// as you can see this is where I got to, and I don't know how to proceed
There are multiple ways to find the nth Prime number, the easiest way is to keep counting the prime numbers from 1 to n. But this is very time consuming otherwise refer to Fermat's theorems or Sieve of Eratosthenes.
private boolean isPrime(int n) {
if (n == 2 || n == 3) return true;
for(int i = 2; i < (int)Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public int nthPrime(int n) {
int number, primeCount;
for(number = 2, primeCount = 0; primeCount < n; number++) {
if (isPrime(number)) {
++primeCount;
}
}
return number;
}
You can try this, it may solve your problem.
class FibonacciExample1 {
public static void main(String args[]) {
int input = 20;
fibonacci(input);
System.out.print("-----------------------------");
prime(input);
}
public static void fibonacci(int input) {
int n1 = 0, n2 = 1, n3, i, count = input;
System.out.print(n1 + " " + n2);
for (i = 2; i < count; ++i) {
n3 = n1 + n2;
System.out.print(" " + n3);
n1 = n2;
n2 = n3;
}
}
public static void prime(int input) {
int i = 0;
int num = 0;
String primeNumbers = "";
for (i = 1; i <= input; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println(primeNumbers);
}
}
I'd make these two programs into simpler, infinite generators that are easier to debug and then sequence:
import java.util.ArrayList;
class Fibonacci {
int a = 0, b = 1;
int next() {
int c = a;
a = b;
b += c;
return a;
}
}
class Prime {
ArrayList<Integer> primes = new ArrayList<>();
int number = 2;
int next() {
if (number == 2) { // special case
primes.add(number);
number = 1;
return 2;
}
outer: while (true) {
number += 2;
for (int divisor: primes) {
if (divisor * divisor > number) {
break outer;
}
if (number % divisor == 0) {
break;
}
}
}
primes.add(number);
return number;
}
}
public class Example {
public static int sequence(int n) {
int nth = -1;
if ((n % 2) == 0) {
Fibonacci fibonacci_generator = new Fibonacci();
for (int i = 0; i < (n / 2) + 1; i++) {
nth = fibonacci_generator.next();
}
} else {
Prime prime_generator = new Prime();
for (int i = 0; i < (n + 1) / 2; i++) {
nth = prime_generator.next();
}
}
return nth;
}
public static void main(String args[]) {
System.out.println(sequence(13)); // 14th element counting from zero
}
}
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
class LCM {
static int GCF(int first, int second){
int FIR = first;
int SEC = second;
ArrayList<Integer> prime1 = new ArrayList<Integer>();
ArrayList<Integer> prime2 = new ArrayList<Integer>();
int n = 1;
// for the specific case of 2
while(true){
if(FIR % 2 == 0){
FIR /= 2;
prime1.add(2);
}
else break;
}
// for the rest of the prime numbers
for(int i = 3;;i = 2*n + 1){
if(FIR < i) break;
if(FIR == i) {
prime1.add(i);
break;
}
if(FIR % i == 0){
FIR /= i;
prime1.add(i);
}
++n;
}
// initialize n back to 1
n = 1;
// for the specific case of 2
while(true){
if(SEC % 2 == 0){
SEC /= 2;
prime2.add(2);
}
else break;
}
// for the rest of the prime numbers
for(int i = 3;; i = 2*n + 1){
if(SEC < i) break;
if(SEC == i){
prime2.add(i);
break;
}
if(SEC % i == 0){
SEC /= i;
prime2.add(i);
}
++n;
}
// Collect all common prime factors to calculate GCF
List<Integer> common = new ArrayList<Integer>(prime2);
common.retainAll(prime1);
int GCF = 1;
for(int i = 0; i < common.size(); i++){
GCF *= common.get(i);
}
return GCF;
}
// End of LCP function
static int lcp(int first, int second){
return (first / GCF(first, second)) * second;
}
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int first = 0;
int second = 0;
while(true){
System.out.print("Enter first number: ");
first = input.nextInt();
System.out.print("Enter second number: ");
second = input.nextInt();
System.out.print("LCM (" + first + ", " + second + ")" + " = ");
System.out.print(lcp(first, second) + "\n");
}
}
}
The code works perfectly when I give it input in one order but it give's the wrong output when I reverse the order of input. For example it outputs
LCM(12, 10) = 56
when I input the two numbers in the order 12 then 10. But it outputs
LCM(10, 12) = 24
when the input is reversed. I tried debugging the code but I couldn't see any obvious problem.
LCM of (10, 12) is 60, NOT 56
If you wish to calculate the LCM of two numbers entered by the user, here's a simpler version that calculates the LCM
class LCM {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int first = 0;
int second = 0;
while(true){
System.out.print("Enter first number: ");
first = input.nextInt();
System.out.print("Enter second number: ");
second = input.nextInt();
System.out.print("LCM ("+first + ","+second+") = " +lcp(first, second) + "\n");
}
}
public static int gcf(int first, int second) {
HashSet<Integer> firstFactors = new HashSet<>();
HashSet<Integer> secondFactors = new HashSet<>();
HashSet<Integer> commonFactors;
//factors of first number
for(int i=1; i<=first; i++) {
if(first%i == 0) {
firstFactors.add(i);
}
}
//factors of second number
for(int i=1; i<=second; i++) {
if(second%i == 0) {
secondFactors.add(i);
}
}
commonFactors = new HashSet<>(firstFactors);
commonFactors.retainAll(secondFactors);
return Collections.max(commonFactors);
}
static int lcp(int first, int second){
return (first / gcf(first, second)) * second;
}
}
What is wrong in my code?
Expected output=1060
I checked with 1000 prime numbers sum. It will show correctly
output 3682913
public class PrimeNumber {
public static void main(String args[]){
int number = 2;
int count = 0;
long sum = 0;
while(count <100){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
You are counting up to 100 primes but not up to 100 numbers.
So your while loop should run up to 100 numbers.
This should be your main method:
int number = 2;
int count = 0;
long sum = 0;
while(number <= 100){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
This would give your output 1060.
Currently, you are counting the first 100 primes, not the primes found in the range 1 - 100. You can lose the count variable entirely here.
Your code can be simplifed as such, using a for loop instead to go from 2 to 100 (1 not included, of course)...
public class PrimeNumber {
public static void main(String args[]) {
long sum = 0;
for (int number = 2; number <= 100; number++) {
if (isPrimeNumber(number)) {
sum += number;
}
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
You can use the below given code to find the sum of first prime numbers between 1 to 100. It will give you correct output.
public class PrimeNumber {
public static void main(String args[]){
int number = 2;
int sum = 0;
while(number <= 100){
if(isPrimeNumber(number)){
sum += number;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
int sqrt = (int) Math.floor(Math.sqrt(number));
for(int i = 2; i <= sqrt; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
import java.util.Scanner;
public class Trial{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = false;
int max = 1000001;
long[] a = new long[max];
a[0] = 2;
int i = 3,j=0;
long sum = 2;
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long sum1 = 0;
int n = in.nextInt();
if(n>=i){
while(i<=n){
for(int y=0;a[y]<=Math.sqrt(i);y++){
if(a[y]==0){
break;
}
else if (i%a[y]==0){
flag = true;
break;
}
}
if(!flag){
a[++j]=i;
sum+=i;
}
flag =false;
i+=2;
}
System.out.println(sum);
}
else{
for(int y=0;a[y]<=n&&a[y]!=0;y++){
sum1+=a[y];
}
System.out.println(sum1);
}
}
}
}
here i stored prime numbers in an array if there is any query for the numbers which are already present in the array first 'if' statement will handle it and simple the sum upto that no. will be printed.This will save a lot time to recalculate the prime numbers and find their sum.
I tried to check the validation of credit card using Luhn algorithm, which works as the following steps:
Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number.
2 * 2 = 4
2 * 2 = 4
4 * 2 = 8
1 * 2 = 2
6 * 2 = 12 (1 + 2 = 3)
5 * 2 = 10 (1 + 0 = 1)
8 * 2 = 16 (1 + 6 = 7)
4 * 2 = 8
Now add all single-digit numbers from Step 1.
4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37
Add all digits in the odd places from right to left in the card number.
6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38
Sum the results from Step 2 and Step 3.
37 + 38 = 75
If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. For example, the number 4388576018402626 is invalid, but the number 4388576018410707 is valid.
Simply, my program always displays valid for everything that I input. Even if it's a valid number and the result of sumOfOddPlace and sumOfDoubleEvenPlace methods are equal to zero. Any help is appreciated.
import java.util.Scanner;
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count - 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
You can freely import the following code:
public class Luhn
{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
}
Link reference: https://github.com/jduke32/gnuc-credit-card-checker/blob/master/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
Google and Wikipedia are your friends. Instead of long-array I would use int-array. On Wikipedia following java code is published (together with detailed explanation of Luhn algorithm):
public static boolean check(int[] digits) {
int sum = 0;
int length = digits.length;
for (int i = 0; i < length; i++) {
// get digits in reverse order
int digit = digits[length - i - 1];
// every 2nd number multiply with 2
if (i % 2 == 1) {
digit *= 2;
}
sum += digit > 9 ? digit - 9 : digit;
}
return sum % 10 == 0;
}
You should work on your input processing code. I suggest you to study following solution:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean repeat;
List<Integer> digits = new ArrayList<Integer>();
do {
repeat = false;
System.out.print("Enter your Credit Card Number : ");
String input = in.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c < '0' || c > '9') {
repeat = true;
digits.clear();
break;
} else {
digits.add(Integer.valueOf(c - '0'));
}
}
} while (repeat);
int[] array = new int[digits.size()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.valueOf(digits.get(i));
}
boolean valid = check(array);
System.out.println("Valid: " + valid);
}
I took a stab at this with Java 8:
public static boolean luhn(String cc) {
final boolean[] dbl = {false};
return cc
.chars()
.map(c -> Character.digit((char) c, 10))
.map(i -> ((dbl[0] = !dbl[0])) ? (((i*2)>9) ? (i*2)-9 : i*2) : i)
.sum() % 10 == 0;
}
Add the line
.replaceAll("\\s+", "")
Before
.chars()
If you want to handle whitespace.
Seems to produce identical results to
return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(cc);
From Apache's commons-validator.
There are two ways to split up your int into List<Integer>
Use %10 as you are using and store it into a List
Convert to a String and then take the numeric values
Here are a couple of quick examples
public static void main(String[] args) throws Exception {
final int num = 12345;
final List<Integer> nums1 = splitInt(num);
final List<Integer> nums2 = splitString(num);
System.out.println(nums1);
System.out.println(nums2);
}
private static List<Integer> splitInt(int num) {
final List<Integer> ints = new ArrayList<>();
while (num > 0) {
ints.add(0, num % 10);
num /= 10;
}
return ints;
}
private static List<Integer> splitString(int num) {
final List<Integer> ints = new ArrayList<>();
for (final char c : Integer.toString(num).toCharArray()) {
ints.add(Character.getNumericValue(c));
}
return ints;
}
I'll use 5 digit card numbers for simplicity. Let's say your card number is 12345; if I read the code correctly, you store in array the individual digits:
array[] = {1, 2, 3, 4, 5}
Since you already have the digits, in sumOfOddPlace you should do something like
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i = 1; i < array.length; i += 2) {
result += array[i];
}
return result;
}
And in sumOfDoubleEvenPlace:
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
for (int i = 0; i < array.length; i += 2) {
result += getDigit(2 * array[i]);
}
return result;
}
this is the luhn algorithm implementation which I use for only 16 digit Credit Card Number
if(ccnum.length()==16){
char[] c = ccnum.toCharArray();
int[] cint = new int[16];
for(int i=0;i<16;i++){
if(i%2==1){
cint[i] = Integer.parseInt(String.valueOf(c[i]))*2;
if(cint[i] >9)
cint[i]=1+cint[i]%10;
}
else
cint[i] = Integer.parseInt(String.valueOf(c[i]));
}
int sum=0;
for(int i=0;i<16;i++){
sum+=cint[i];
}
if(sum%10==0)
result.setText("Card is Valid");
else
result.setText("Card is Invalid");
}else
result.setText("Card is Invalid");
If you want to make it use on any number replace all 16 with your input number length.
It will work for Visa number given in the question.(I tested it)
Here's my implementation of the Luhn Formula.
/**
* Runs the Luhn Equation on a user inputed CCN, which in turn
* determines if it is a valid card number.
* #param c A user inputed CCN.
* #param cn The check number for the card.
* #return If the card is valid based on the Luhn Equation.
*/
public boolean luhn (String c, char cn)
{
String card = c;
String checkString = "" + cn;
int check = Integer.valueOf(checkString);
//Drop the last digit.
card = card.substring(0, ( card.length() - 1 ) );
//Reverse the digits.
String cardrev = new StringBuilder(card).reverse().toString();
//Store it in an int array.
char[] cardArray = cardrev.toCharArray();
int[] cardWorking = new int[cardArray.length];
int addedNumbers = 0;
for (int i = 0; i < cardArray.length; i++)
{
cardWorking[i] = Character.getNumericValue( cardArray[i] );
}
//Double odd positioned digits (which are really even in our case, since index starts at 0).
for (int j = 0; j < cardWorking.length; j++)
{
if ( (j % 2) == 0)
{
cardWorking[j] = cardWorking[j] * 2;
}
}
//Subtract 9 from digits larger than 9.
for (int k = 0; k < cardWorking.length; k++)
{
if (cardWorking[k] > 9)
{
cardWorking[k] = cardWorking[k] - 9;
}
}
//Add all the numbers together.
for (int l = 0; l < cardWorking.length; l++)
{
addedNumbers += cardWorking[l];
}
//Finally, check if the number we got from adding all the other numbers
//when divided by ten has a remainder equal to the check number.
if (addedNumbers % 10 == check)
{
return true;
}
else
{
return false;
}
}
I pass in the card as c which I get from a Scanner and store in card, and for cn I pass in checkNumber = card.charAt( (card.length() - 1) );.
Okay, this can be solved with a type conversions to string and some Java 8
stuff. Don't forget numbers and the characters representing numbers are not the same. '1' != 1
public static int[] longToIntArray(long cardNumber){
return Long.toString(cardNumber).chars()
.map(x -> x - '0') //converts char to int
.toArray(); //converts to int array
}
You can now use this method to perform the luhn algorithm:
public static int luhnCardValidator(int cardNumbers[]) {
int sum = 0, nxtDigit;
for (int i = 0; i<cardNumbers.length; i++) {
if (i % 2 == 0)
nxtDigit = (nxtDigit > 4) ? (nxtDigit * 2 - 10) + 1 : nxtDigit * 2;
sum += nxtDigit;
}
return (sum % 10);
}
private static int luhnAlgorithm(String number){
int n=0;
for(int i = 0; i<number.length(); i++){
int x = Integer.parseInt(""+number.charAt(i));
n += (x*Math.pow(2, i%2))%10;
if (x>=5 && i%2==1) n++;
}
return n%10;
}
public class Creditcard {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String cardno = sc.nextLine();
if(checkType(cardno).equals("U")) //checking for unknown type
System.out.println("UNKNOWN");
else
checkValid(cardno); //validation
}
private static String checkType(String S)
{
int AM=Integer.parseInt(S.substring(0,2));
int D=Integer.parseInt(S.substring(0,4)),d=0;
for(int i=S.length()-1;i>=0;i--)
{
if(S.charAt(i)==' ')
continue;
else
d++;
}
if((AM==34 || AM==37) && d==15)
System.out.println("AMEX");
else if(D==6011 && d==16)
System.out.println("Discover");
else if(AM>=51 && AM<=55 && d==16)
System.out.println("MasterCard");
else if(((S.charAt(0)-'0')==4)&&(d==13 || d==16))
System.out.println("Visa");
else
return "U";
return "";
}
private static void checkValid(String S) // S--> cardno
{
int i,d=0,sum=0,card[]=new int[S.length()];
for(i=S.length()-1;i>=0;i--)
{
if(S.charAt(i)==' ')
continue;
else
card[d++]=S.charAt(i)-'0';
}
for(i=0;i<d;i++)
{
if(i%2!=0)
{
card[i]=card[i]*2;
if(card[i]>9)
sum+=digSum(card[i]);
else
sum+=card[i];
}
else
sum+=card[i];
}
if(sum%10==0)
System.out.println("Valid");
else
System.out.println("Invalid");
}
public static int digSum(int n)
{
int sum=0;
while(n>0)
{
sum+=n%10;
n/=10;
}
return sum;
}
}
Here is the implementation of Luhn algorithm.
public class LuhnAlgorithm {
/**
* Returns true if given card number is valid
*
* #param cardNum Card number
* #return true if card number is valid else false
*/
private static boolean checkLuhn(String cardNum) {
int cardlength = cardNum.length();
int evenSum = 0, oddSum = 0, sum;
for (int i = cardlength - 1; i >= 0; i--) {
System.out.println(cardNum.charAt(i));
int digit = Character.getNumericValue(cardNum.charAt(i));
if (i % 2 == 0) {
int multiplyByTwo = digit * 2;
if (multiplyByTwo > 9) {
/* Add two digits to handle cases that make two digits after doubling */
String mul = String.valueOf(multiplyByTwo);
multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
}
evenSum += multiplyByTwo;
} else {
oddSum += digit;
}
}
sum = evenSum + oddSum;
if (sum % 10 == 0) {
System.out.println("valid card");
return true;
} else {
System.out.println("invalid card");
return false;
}
}
public static void main(String[] args) {
String cardNum = "4071690065031703";
System.out.println(checkLuhn(cardNum));
}
}
public class LuhnAlgorithm {
/**
* Returns true if given card number is valid
*
* #param cardNum Card number
* #return true if card number is valid else false
*/
private static boolean checkLuhn(String cardNum) {
int cardlength = cardNum.length();
int evenSum = 0, oddSum = 0, sum;
for (int i = cardlength - 1; i >= 0; i--) {
System.out.println(cardNum.charAt(i));
int digit = Character.getNumericValue(cardNum.charAt(i));
if (i % 2 == 0) {
int multiplyByTwo = digit * 2;
if (multiplyByTwo > 9) {
/* Add two digits to handle cases that make two digits after doubling */
String mul = String.valueOf(multiplyByTwo);
multiplyByTwo = Character.getNumericValue(mul.charAt(0)) + Character.getNumericValue(mul.charAt(1));
}
evenSum += multiplyByTwo;
} else {
oddSum += digit;
}
}
sum = evenSum + oddSum;
if (sum % 10 == 0) {
System.out.println("valid card");
return true;
} else {
System.out.println("invalid card");
return false;
}
}
public static void main(String[] args) {
String cardNum = "8112189875";
System.out.println(checkLuhn(cardNum));
}
}
Hope it may works.
const options = {
method: 'GET',
headers: {Accept: 'application/json', 'X-Api-Key': '[APIkey]'}
};
fetch('https://api.epaytools.com/Tools/luhn?number=[CardNumber]&metaData=true', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
So this is my code so far.
public int getsum (int n){
int num = 23456;
int total = 0;
while (num != 0) {
total += num % 10;
num /= 10;
}
}
The problem is that i cant/know how to change this into a recursive method
Im kind of new with recursion and i need some help on implementing this method to change it so its recursive.
Short, recursive and does the job:
int getsum(int n) {
return n == 0 ? 0 : n % 10 + getsum(n/10);
}
Here it is,
//sumDigits function
int sumDigits(int n, int sum) {
// Basic Case to stop the recursion
if (n== 0) {
return sum;
} else {
sum = sum + n % 10; //recursive variable to keep the digits sum
n= n/10;
return sumDigits(n, sum); //returning sum to print it.
}
}
An example of the function in action:
public static void main(String[] args) {
int sum = sumDigits(121212, 0);
System.out.println(sum);
}
public int sumDigits(int n) {
return (n - 1) % 9 + 1;
}
public static int sumOfDigit(int num){
int sum=0;
if (num == 0)
return sum;
sum = num%10 + sumOfDigit(num/10);
return sum;
}
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
System.out.print("Input num : ");
int num=input.nextInt();
int s=sumOfDigit(num);
System.out.println("Sum = "+s);
}
}
Try this:
int getSum(int num)
{
total = total + num % 10;
num = num/10;
if(num == 0)
{
return total;
} else {
return getSum(num);
}
}
int getSum(int N)
{
int totalN = 0;
totalN += (N% 10);
N/= 10;
if(N == 0)
return totalN;
else
return getSum(N) + totalN;
}
public static int digitSum (int n)
{
int r = n%10; //remainder, last digit of the number
int num = n/10; //the rest of the number without the last digit
if(num == 0)
{
return n;
} else {
return digitSum (num) + r;
}}
This works for positive numbers.
public int sumDigits(int n) {
int sum = 0;
if(n == 0){
return 0;
}
sum += n % 10; //add the sum
n /= 10; //keep cutting
return sum + sumDigits(n); //append sum to recursive call
}
import java.util.Scanner;
public class Adder {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
System.out.println();
int number = input.nextInt();
System.out.println("The sum of the digits is " +adder(number));
}
public static int adder(int num){
int length = String.valueOf(num).length();
int first , last , sum;
if (length==1){
return num;
}
else
{
first = num /10;
last = num % 10;
sum = last + adder(first);
}
return sum;
}
}
I see a lot of solutions on here, but not one in which seems as simple as what follows. I've tested it countless times and it works no problem:
public int sumDigits(int n) {
if (n == 0){
return 0;
}
else{
return n%10 + sumDigits(n/10);
}
}
I used recursion method in java for finding the sum of digits of a number
public class recursion_practice {
static int sum(int n) {
int sum = 0;
if (n > 0) {
int d = n % 10;
sum += d;
return sum + sum(n / 10);
} else return 0;
}
public static void main(String[] args) {
int x = 123;
System.out.println(sum(x)); // it will print 6 as 1+2+3=6
}
}
#include <iostream>
int useRecursion(int x);
using namespace std;
int main(){
int n;
cout<<"enter an integer: ";
cin>>n;
cout<<useRecursion(n)<<endl;
return 0;
}
int useRecursion(int x){
if(x/10 == 0)
return x;
else
return useRecursion(x/10) + useRecursion(x%10);
}
I think it's the shortest so far. The input thing is up too you, though.
public static int getSum(int input) { //example: input=246
int sum=0;
if (input%10==input) { //246%10=6;
return input%10; //2%10=2
}
return input%10+getSum((input-input%10)/10); //(246-6)/10=24; 24%10=4
}