I wrote the armstrong number question in java by myself(sorry if its silly, I'm new to programming).
The "result is supposed to give 1 value when i enter a coorect armstrong number but it gives 0,why?
Code-
import java.util.Scanner;
public class Exercise1_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int result = 0;
int i = 0;
int sum = 0;
while (n > 0) {
i = n % 10;
sum += i * i * i;
n = n / 10;
}
if (sum == n) {
System.out.print("1");
} else {
System.out.print("0");
}
n is changed in the while loop. After the while loop n == 0 (if n was entered as a non-negative number). This the only case where sum == n is true will be sum == 0. You need to introduce a temporary variable which is modified in the loop and keep n unchanged.
int temp = n;
while (temp > 0) {
int i = temp % 10;
sum += i * i * i;
temp /= 10;
}
N.B. result is not used, i not decalred inside the while loop
This piece of code is supposed to take 2 numbers and find the factorial of every number between and incuding said numbers. I'm not getting the right output however and cant figure out what im doing wrong.
Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();
if (n > 0 && m > 0) //want factorial greater than zero
for(int j = n; j <= m; j++)
{
for(int i = 1; i <= j; i++)
{
result = result * i; //find factorial
}
System.out.println(result);
}
if(n <= 0 || m <= 0) //if value is les than zero
{
System.out.println("Not Valid!");
}
Something like should work:
public class RangeFactorial {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int max = scan.nextInt();
int min = scan.nextInt();
if (max < 0 || min < 0) {
System.out.println("Invalid Params");
}
for (int i = min; i <= max; i++) {
System.out.println("Factorial for " + i + " is: " + factorial(i));
}
scan.close();
}
private static int factorial(int i) {
if (i <= 1) {
return 1;
}
return i * factorial(i-1);
}
}
Note that the code assumes that max/min fall in place, I've omitted the logic to decide the max/min integer from the given inputs. You'll need to add this.
You forgot to reset 'result' to 1.
Also, there is no need to have another if statement if it is only checking for the negation of the first one, just use an else.
I also fixed the code style guidelines to follow the standard Java ones as:
The curly bracket style you used is the one usually used in C/C++.
Even if if-statements or loops contain only one line after them, it is good etiquette to use curly brackets anyway, in Java.
Take a look at the Google Java Style Guide if you want to know more.
Scanner scan = new Scanner(System.in);
long result = 1;
int m = scan.nextInt();
int n = scan.nextInt();
scan.close();
if (n > 0 && m > 0){
for(int j = n; j <= m; j++){
result = 1; //You forgot to reset 'result'
for(int i = 1; i <= j; i++){
result *= i;
}
System.out.println(result);
} else { // No need for another if statement
System.out.println("Not Valid!");
}
I'm new to java/programming in general and this is a homework assignment. This is what I have so far: When I run it I get the powers of 2 below the n input. example if n = 50, output is 2 + 4 + 8 + 16 + 32 + = -2
I would like the + after 32 to be gone and I don't know how to properly sum it. I would want the sum to = 62 in this case. I tried using string builder to take off the last two characters but that isn't working for me.
import java.util.Scanner;
public class Powers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Enter the upper limit: ");
n = scan.nextInt();
int sum = 0;
int power = 1;
for (int i = 0; i <= n; i++) {
power = 2 * power;
if (power < n && 0 < power) {
System.out.print(power + " + ");
}
sum = sum + power;
}
System.out.println(" = " + sum);
}
}
There are multiple issues here:
When reaching the upper limit you simply stop doing the output but continue doing the summation.
You use the upper limit as the number of iterations, so in case of 50 in your example, you do a sum of all values between 1 and 2^50, which is the reason why the result is negative, because the sum became larger than the maximum number an int can keep.
Concerning your question how to break a loop, there is break ;-)
Your print is always outputting a + which is why you have the + = in your output. Change the output to something like this:
if (power < n && 0 < power) {
if (i != 0) {
System.out.print(" + ");
}
System.out.print(power);
}
I've added some functionality to your code.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Type number:");
Scanner scanner = new Scanner(System.in);
int n = 0;
while (n == 0) { // to ask again if "n" is zero.
n = scanner.nextInt();
}
if (n != 0) {
scanner.close(); // to prevent resource leak
int sum = 0;
int power = 1;
for (int i = 0; i < n; i++) {
power *= 2;
sum += power;
System.out.print(power + " ");
if (sum + power * 2 < 0 | i == n - 1) {
// Should we step to the next iteration?
// If next "sum" will be bigger than the max value for
// integers
// or if this iteration is the last - it will type "sum",
// break "for" cycle and go the next line of code after
// "for" cycle.
// So in this case System.out.print("+ "); won't be
// executed.
System.out.print("= " + sum);
break;
}
System.out.print("+ ");
}
}
}
}
Hi can some one please explain me the below derangement/permutation program in a simple way.
From past one week I am banging my head to understand the program. I have understood all the methods but I am not able to understand the "else part". I have tried debugging the program but didn't get clarity to what is happening in the else part.
import java.util.Scanner;
public class Deranged {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number");
int num = s.nextInt();
System.out.println("Number :" + num);
int size = digitSize(num);
System.out.println("Size :" + size);
System.out.println("Permutation :" + fact(size));
int swap = fact(size);
int array[] = digitArray(num, size);
if (size < 3) {
if (size < 2) {
System.out.print(num);
} else {
System.out.println(array[0] + "" + array[1]);
System.out.println(array[1] + "" + array[0]);
}
} else { // NEED CLARITY FROM HERE
int i = 2;
for (int outer = 0; outer <= size - 1; outer++) {
int fix = array[0];
for (int j = 1; j <= swap / size; j++) {
if (i == size) {
i = 2;
}
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
i++;
int uniqueNo = fix;
for (int k = 1; k < size; k++) {
uniqueNo = (uniqueNo * 10) + array[k];
}
System.out.println(j + ": " + uniqueNo);
}
int t = array[0];
if ((outer + 1) > size - 1) {
array[0] = array[outer];
array[outer] = t;
} else {
array[0] = array[outer + 1];
array[outer + 1] = t;
}
}
}
}
public static int fact(int num) {
int factNo = 1;
for (int i =num; i > 0; i--)
{
factNo = factNo * i;
}
return factNo;
}
public static int digitSize(int num) {
//int count = String.valueOf(num).length();
// return count;
int count = 0;
while(num>0)
{
num/=10;
count++;
}
return count;
}
public static int[] digitArray(int num, int size) {
int count[] = new int[size];
int i = size - 1, rem;
while (num > 0) {
rem = num % 10;
count[i] = rem;
num = num / 10;
i--;
}
return count;
}
}
In the code size is the number of digits in your number and swap is the factorial of the number of digits. For example, if you enter a 5 digit number the fact function calculates 5 * 4 * 3 * 2 * 1. array is just a list of the digits you entered, ordered from the least significant digit to the most significant.
So here is the pseudo code for the case where the number of digits is 3 or greater. I've interleaved the code to make it clearer.
i = 2
For each digit in the array of digits indexed by outer
- Set fix to the digit currently stored in the first element of the array
int i = 2;
for (int outer = 0; outer <= size - 1; outer++) {
int fix = array[0];
For each index j from 1 to the factorial of the number of digits divided by number of digits
- If i is equal to the number of digits, set i equal to 2
- Swap digit i-1 with digit i in the digit array
- Increment I
int fix = array[0];
for (int j = 1; j <= swap / size; j++) {
if (i == size) {
i = 2;
}
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
i++;
Set uniqueNo to the decimal number that the digit array currently represents, except that fix is the least significant digit
Print the uniqueNo for the current value of j
int uniqueNo = fix;
for (int k = 1; k < size; k++) {
uniqueNo = (uniqueNo * 10) + array[k];
}
System.out.println(j + ": " + uniqueNo);
If the current value of outer is the last element in the digit array
- Swap the first digit with the last digit in the array
Else
- Swap the first digit of the array with the digit at outer+1
int t = array[0];
if ((outer + 1) > size - 1) {
array[0] = array[outer];
array[outer] = t;
} else {
array[0] = array[outer + 1];
array[outer + 1] = t;
}
The code is basically iterating factorial/number of digit times for each digit of the number that was input and rearranging the digits with each iteration in a way that wraps around from the last digit to the first. It's difficult to understand partly because the variable names are uninformative.
The number of permutations of n distinct objects is n! (factorial), so the code is just listing all possible permutations of the digits of the number that was input. If there are only 2 digits, there are only two permutations, and of course 1 digit has only one permutation, so those are special cases. If you iterate through each digit, the maximum number of permutations keeping one digit "fixed" is factorial/number of digits.
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));