Problem Statement
Prepaid services are very popular in different wireless systems. When using a prepaid account, a user buys a card and submits its unique code to the provider. The provider checks whether the submitted code is valid.
You will be given a String code, representing a code of a card. Return the value of the card if code is valid, and -1 otherwise.
You can determine the value of the card using the following algorithm:
First, assign 0-based indices to all prime numbers in ascending order, starting from 2. Thus, for example, numbers 2, 3, 5 and 17 will get indices 0, 1, 2 and 6 respectively. Then get p - a prime number with the index equal to the last digit of code. Sum up all the other digits of code to determine the number S. If (S % p) is not zero, the code is invalid and your program should return -1. Otherwise, return (S/p), which is the value of the card.
You will be given a String code, representing a code of a card. Return the value of the card if code is valid, and -1 otherwise.
You can determine the value of the card using the following algorithm:
First, assign 0-based indices to all prime numbers in ascending order, starting from 2. Thus, for example, numbers 2, 3, 5 and 17 will get indices 0, 1, 2 and 6 respectively. Then get p - a prime number with the index equal to the last digit of code. Sum up all the other digits of code to determine the number S. If (S % p) is not zero, the code is invalid and your program should return -1. Otherwise, return (S/p), which is the value of the card.
Definition
- Class:
- ValidCode
- Method:
- isCodeValid
- Parameters:
- String
- Returns:
- int
- Method signature:
- int isCodeValid(String code)
- (be sure your method is public)
Notes
- The first ten primes are {2,3,5,7,11,13,17,19,23,29}.
Constraints
- code will contain between 3 and 50 digits ('0'-'9'), inclusive.
Examples
"642"
Returns: 2
First, we get 5 as the prime with the index equal to 2. Then, we sum the first two digits of code, getting 10. (10 % 5) is equal to 0, so code is valid and we should return 2 = 10/5;"643"
Returns: -1
The sum of the first two digits is the same, but p is now the prime with index 3, which is 7 - so code is invalid."00000000"
Returns: 0
This card is valid, though its value is equal to 0."611589149845189548791840829969221274009432844489"
Returns: 8
The last digit is '9', so p = 29."9733222733345054556129293835597"
Returns: -1