I have a beginner question about generating Fibonacci numbers in Java.
In this java program, the method should print Fibonnacci numbers sequence from BeginIndex to LastIndex, so it should print "Hi" (instead of number) if the number is a multiple of 5, print "I am" if the number is a multiple of 7 and print "Hi I am me" if the number is a multiple of 35. I am not really sure on how to do this.
class FibonacciClass {
public static void main(String args[] ) throws Exception {
generatefibonacci(10, 20);
generatefibonacci(0, 1);
}
private static void generatefibonacci(int BeginIndex, int LastIndex) {
}
Another possibility:
private static void generateFibonacci(int beginIndex, int lastIndex) {
int len = lastIndex + 1;
int[] fib = new int[len];
fib[0] = 0;
fib[1] = 1;
// Building Fibonacci sequence from beginIndex through lastIndex
for (int i = 2; i < len; ++i)
fib[i] = fib[i-1] + fib[i-2];
// Printing
for (int index = beginIndex; index <= lastIndex; ++index) {
if ((fib[index] % 5 == 0) && (fib[index] % 7 == 0)) {
System.out.println("Hi I am me");
}
else if (fib[index] % 5 == 0) {
System.out.println("Hi");
}
else if (fib[index] % 7 == 0) {
System.out.println("I am");
}
else {
System.out.println(fib[index]);
}
}
}
What you're looking for is the modulus operator, %. It will return the remainder of division by its operands. So, receiving a true value from if (x % 5 == 0 && x % 7 == 0) would represent the number x being both multiples of 5 and 7. If this case does not pass, you should use else if statements to individually check for if x is a multiple of 5 and then another for if x is a multiple of 7, with each if branch calling System.out.println("x is a multiple of y");
Everytime generatefibonacci has produced a result you have to check with modulo (%).
Like this:
private static generatefibonnacci(int startIndex, int endIndex){
int result = -1;
//do generating stuff
//and set "result" to generated fibonacci
//and then
if(result%5==0){
System.out.println("Hi");
} else if(result%7==0){
System.out.println("Hi I am me!");
} //and so on
So this is just a little example.
Have fun
private static void generatefibonacci(int BeginIndex, int LastIndex) {
int[] numbers = new int[LastIndex + 2]; //creates an array to put fibonacci numbers in
numbers[0] = 1; numbers[1] = 1;
for(int i = 2; i <= LastIndex; i ++){
numbers[i] = numbers[i - 1] + numbers[i - 2]; //generates the Fibonacci Sequence
}
for(int i = BeginIndex; i <= LastIndex; i ++){
if(numbers[i] % 5 == 0 && numbers[i] % 7 == 0){//if the remainder when the numbers/5 equals 0 and the remainder when the numbers/7 equals 0
System.out.println("Hello I am me");
}
else if(numbers[i] % 5 == 0){ //if the remainder when the numbers/5 equals 0
System.out.println("I am");
}
else if(numbers[i] % 7 == 0){ //if the remainder when the numbers/7 equals 0
System.out.println("Hi");
}
else{ //if none of the above three conditions are true
System.out.println(numbers[i]);
}
}
}
Related
This is in java. I am trying to write a method that randomly generates a number 1000000 - 2000000, then takes the frequency of each digit. We cannot use arrays or for loops.
For example, if the number is 1880500, the output would be:
(1, 1), (8, 2), (5, 1), (0, 3).
However, my output looks like this: (1, 1), (8, 2), (8, 1), (0, 3), (0, 2), (5, 1), (0, 1).
So my problem is that I don't know how to stop a digit from printing twice if that digit was already printed. Thanks
This is my code for the method:
int num = 1000000 + (int)(Math.random() * (2000000 - 1000000 + 1));
System.out.println("The generated number is: " + num);
int oneDigit = num % 10;
while (num > 0) {
int oneDigitCount = 0;
int num2 = num;
while (num2 > 0) {
if (num2 % 10 == oneDigit) {
oneDigitCount++;
}
num2 /= 10;
}
if (num < 10 && oneDigit != newDigit) {
System.out.printf("(%d, %d)", oneDigit, oneDigitCount);
}
else {
System.out.printf("(%d, %d), ", oneDigit, oneDigitCount);
}
num /= 10;
oneDigit = num % 10;
You're currently parsing your number n times, where n is the number of digits. So, if the number is 1880500, you're counting the number of 0's in 1880500, then you're counting the number of 0's in 188050, then you're counting the number of 5's in 18805, then the number of 0's in 1880, etc.
Since you apparently can't use arrays, maps, or for loops, we need a slightly different approach. Fortunately, since we're dealing with a known set of digits, we can kind of invert the logic here. Instead of getting the digits from the number itself (which is ultimately what's causing the duplication), we can use a while loop to loop through the digits 0 - 9, and look for them in the original number.
int num = 1000000 + (int) (Math.random() * (2000000 - 1000000 + 1));
System.out.println("The generated number is: " + num);
int i = 0;
while (i < 10) {
int count = 0;
int temp = num;
while (temp > 0) {
int digit = temp % 10;
if (digit == i) {
count++;
}
temp /= 10;
}
if (count > 0) {
System.out.printf("(%d, %d), ", i, count);
}
i++;
}
You'll notice that this is essentially identical to a for loop. For the most part, loops are loops, and the distinction between while and for loops is just a convenience.
Converting your random number to a String, we are able to get the character in that string and count how many times the character appears then remove it from the string. Loop through the string until there are no characters left.
public void printFrequency(int number) {
//convert the number to a string
String numString = String.valueOf(number);
//loop until the string length is replaced
while (numString.length() > 0) {
// get the first "character" in the string
String char1 = String.valueOf(numString.charAt(0));
//check to see how many of the characters were replaced with empty
int count = numString.length() - numString.replaceAll(char1, "").length();
//print
System.out.println(String.format("(%s, %d)", char1, count));
//trim the string
numString = numString.replaceAll(char1, "");
}
}
Output
(1, 1)
(8, 2)
(0, 3)
(5, 1)
I think, in general, it's better to create a method and retrieve a String as a result instead of using System.out. In case you have restrictions, just be simple:
public static String calc(int num) {
int zero = 0;
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int seven = 0;
int eight = 0;
int nine = 0;
while (num > 0) {
int n = num % 10;
if (n == 0)
zero++;
else if (n == 1)
one++;
else if (n == 2)
two++;
else if (n == 3)
three++;
else if (n == 4)
four++;
else if (n == 5)
five++;
else if (n == 6)
six++;
else if (n == 7)
seven++;
else if (n == 8)
eight++;
else
nine++;
num /= 10;
}
StringBuilder buf = new StringBuilder();
if (zero > 0)
buf.append("(0,").append(zero).append("),");
if (one > 0)
buf.append("(1,").append(one).append("),");
if (two > 0)
buf.append("(2,").append(two).append("),");
if (three > 0)
buf.append("(3,").append(three).append("),");
if (four > 0)
buf.append("(4,").append(four).append("),");
if (five > 0)
buf.append("(5,").append(five).append("),");
if (six > 0)
buf.append("(6,").append(six).append("),");
if (seven > 0)
buf.append("(7,").append(seven).append("),");
if (eight > 0)
buf.append("(8,").append(eight).append("),");
if (nine > 0)
buf.append("(9,").append(nine).append("),");
if (buf.length() > 0)
buf.setLength(buf.length() - 1);
return buf.toString();
}
Demo. Buy the way, you have a sorted result.
System.out.println(calc(1880500)); // (0,3),(1,1),(5,1),(8,2)
I'm not sure why my ct is not going all the way to 100 even though I clearly set it to go until it reaches 100.
public class PalindromicPrime
{
public static void main(String [] args)
{
int ct = 0;
while(ct < 100)
{
if(isPalindrome(ct) && isPrime(ct))
{
if(ct % 10 != 0)
{
System.out.print(ct + " ");
}
else
{
System.out.print("\n");
}
}
ct++;
}
public static boolean isPalindrome(int p)
{
int palindrome = p;
int reverse = 0;
while (palindrome != 0)
{
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
if (p == reverse)
{
return true;
}
return false;
}
I'm assuming my isPrime code is wrong since I'm getting a 4 in my output. What's wrong with this method?
public static boolean isPrime(int p)
{
for(int i = 2; i < p/2; i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
First change you should do in your method isPrime() is change this line
for(int i = 2; i < p/2; i++)
to
for(int i = 2; i <= p/2; i++) // you can easily find the reason why it is necessary(=)
And also you are printing palindromic numbers less than 100 which are prime,not first 100 palindrome numbers, if you want to print first 100 palindrome numbers you can take another counter which will keep track of the numbers printed.
You can modify your main method like this:
public static void main(String [] args)
{
int ct = 0,n=0; // n to count numbers printed/found
while(n < 100) // change the condition to check n<100
{
if(isPalindrome(ct) && isPrime(ct))
{
System.out.print(ct + " ");
if(n % 10 == 0)
{
System.out.println();
}
n++; // incementing n after a number is found!
}
ct++;
}
}
Your palindrome method is fine. It's your isPrime method that's not working because to check if a number is prime, you're supposed to test factors up to the square root of the number. So a simple change in the condition should do it,
public static boolean isPrime(int p)
{
for(int i = 2; i <= Math.sqrt(p); i++)
{
if(p % i == 0)
{
return false;
}
}
return true;
}
}
Change your isPrime function to following (replace < with <= as 4/2 is 2 and loop will not run at all for p=4):
public static boolean isPrime(int p) {
for (int i = 2; i <= p / 2; i++) {
if (p % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int ct = 2;
int count = -1;
while (count < 99) {
if (isPalindrome(ct) && isPrime(ct)) {
count++;
if (count % 10 == 0) {
System.out.print("\n" );
}
System.out.print(ct + " ");
}
ct++;
}
}
The only numbers that are palindrome and prime and less than 100 are:
1 2 3 5 7 11
Try changing the value of 100 to 102. Then you get the following output as 101 is the next palindromic prime after 11:
1 2 3 5 7 11 101
In my code, I want charSum to return 'X' if the remainder is 10 when the sum of 9 digits is divided by 9. I tried both charSum = 'X' and charSum = (char) 88 and neither works. Something in my algorithm must be wrong. Please help.
public static char getCheckSum(String isbn) {
int sum = 0;
for (int i = 0; i < isbn.length(); i++) {
int[] num = new int[isbn.length()];
num[i] = Character.getNumericValue(isbn.charAt(i));
sum = sum + num[i];
}
int last = (sum % 11);
char charSum;
if (last == 10){
charSum = 'X';
} else {
charSum = (char) (last + 48);
}
return charSum;
}
public static String formatISBNWithHyphens(String isbn) {
// original isbn: 123456789
// possible new isbn: 1-234-56789-X
char isbn10 = getCheckSum(isbn);
String isbn10Str = isbn + Character.toString(isbn10);
// char[] c = new char[isbn10Str.length()]; *leaving this here for future learning.
String[] cStr = new String[isbn10Str.length()];
String isbnStr = "";
for (int i = 0; i < isbn10Str.length(); i++){
cStr[i] = Character.toString(isbn10Str.charAt(i));
// c[i] = isbn10Str.charAt(i); *leaving this here for future learning.
if (i == 0 || i == 3 || i == 8 ) {
cStr[i] += '-';
}
isbnStr += cStr[i];
}
return isbnStr;
}
It works fine. If I run it with 933456789 (the sum of which is 54, so 54 % 11 = 10), the getCheckSum() method returns X as expected.
However, this does not seem like the correct way to calculate an ISBN-10 checksum. According to Wikipedia:
The 2001 edition of the official manual of the International ISBN
Agency says that the ISBN-10 check digit – which is the last digit of
the ten-digit ISBN – must range from 0 to 10 (the symbol X is used for
10), and must be such that the sum of all the ten digits, each
multiplied by its (integer) weight, descending from 10 to 1, is a
multiple of 11.
I've implemented it according to the specification as follows:
public static char getCheckDigit(String isbn) {
if (isbn == null || !isbn.matches("[0-9]{9,}")) {
throw new IllegalArgumentException("Illegal ISBN value");
}
int sum = 0;
for (int i = 0; i < 9; i++) {
sum += ((10 - i) * Character.digit(isbn.charAt(i), 10));
}
int check = ((11 - (sum % 11)) % 11);
return check == 10 ? 'X' : Character.forDigit(check, 10);
}
Applied to a couple of ISBN values I found on the same Wikipedia page:
getCheckDigit("097522980"); // --> returns 'X'
getCheckDigit("094339604"); // --> returns '2'
getCheckDigit("999215810"); // --> returns '7'
public class HelloWorld{
public static char getCheckSum(String isbn) {
int sum = 0;
for (int i = 0; i < isbn.length(); i++) {
int[] num = new int[isbn.length()];
num[i] = Character.getNumericValue(isbn.charAt(i));
System.out.println(num[i]);
sum = sum + num[i];
System.out.println(sum);
}
int last = (sum % 11);
char charSum;
if (last == 10){
charSum = 'X';
} else {
charSum = (char) (last + 48);
}
return charSum;
}
public static void main(String []args){
String isbn="123456787";
// possible new isbn: 1-234-56789-X
char isbn10 = getCheckSum(isbn);
System.out.println(isbn10);
}
}
it's working fine :)
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));
I'm having some trouble in completing this factor generator from my programming class. It's supposed to take a number, and print out all the factors using the nextFactor method. When I set the number to factor to let's say 150, it prints out "1 2 3 5", where it's supposed to print "2 3 5 5". So, where should I go from here? I've looked at Java - Factor Generator program nextfactor method, but it didn't awnser any of my inqueries
public class FactorGenerator
{
//user inputs int from scanner in FactorTester class
public FactorGenerator(int i)
{
num = i;
}
//Checks to see if num can be factored, but does not factor it.
//Goes through all possible factors of num and returns true if the remainder == 0
public boolean hasMoreFactors()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
return true;
}
}
return false;
}
//Actually factors num and prints out the factor at the end of every loop.
public void nextFactor()
{
for(int i = 1; i < num; i++)
{
//check if the remainder is anything other then 0
if(num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
private int num;
}
try this factors can duplicate so you need to loop until you have extracted all the instances of that factor
public void nextFactor()
{
for(int i = 2; i <= num; i++)
{
//check if the remainder is anything other then 0
while (num >= i && num % i == 0)
{
System.out.println(i);
num /= i;
}
}
System.out.println("Done.");
}
an alternative way is to do the increment in the body of the loop
public void nextFactor()
{
for(int i = 2; i <= num;)
{
//check if the remainder is anything other then 0
if (num % i == 0)
{
System.out.println(i);
num /= i;
} else {
i++;
}
}
System.out.println("Done.");
}
For starters, it will always print out 1 because any integer / 1 will always have remainder of zero. You can start i from 2 instead of 1 in your for if you want to skip 1.
I'd suggest something like this: (note this is based in part on BevynQ's answer below):
for(int i = 2; i <= num; i++){
while (num >= i && num % i == 0) {
System.out.println(i);
num /= i;
}
}