Why does my loop increment 1 over the value needed? - java

This is my first CS class ever, and I'm trying to learn everything the best that can. In this loop I am trying to find valid mastercard numbers using Luhn's formula. The program works, but it's been bugging me that my final for loop outputs 1 number over the correct value, unless I subtract 1 from z after the loop finishes iterating. For example: if the sum = 56 , then z would = 5 , when the correct answer would be 4. How can I fix this going forward?
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class MCGenerator {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
Random rand = new Random();
System.out.print("How many Mastercard numbers would you like to generate? ");
int quantity = scnr.nextInt();
int x;
int use;
int range;
int appendI;
Long appendL;
String firstDigits;
String append;
String preliminary;
int y;
int c;
int sum;
int z;
int findDigit;
String lastNum;
String cardNumber;
System.out.println("\nHere you go, have fun: ");
for(x = 0; x < quantity; x++ ) {
use = rand.nextInt(2 - 1 + 1) +1;
if(use == 1) {
range = rand.nextInt(55 - 51 + 1) + 51;
}
else {
range = rand.nextInt(272099 - 222100 +1) + 222100;
}
if(range < 56) {
appendL = ThreadLocalRandom.current().nextLong(1000000000000L, 10000000000000L);
append = String.valueOf(appendL);
}
else {
appendI = rand.nextInt(999999999 - 100000000 + 1) + 100000000;
append = String.valueOf(appendI);
}
firstDigits = String.valueOf(range);
preliminary = firstDigits + append;
for(y = 0, sum = 0; y < 15; y++ ) {
c = preliminary.charAt(y) - '0';
if(y % 2 == 0){
c *= 2;
}
if(c > 9) {
c -= 9;
}
sum += c;
}
for(z = 0, findDigit = sum; findDigit > 0; z++){
findDigit = sum + z;
findDigit %= 10;
}
z -= 1;
lastNum = String.valueOf(z);
cardNumber = preliminary + lastNum;
System.out.println(cardNumber);
}
}
}

Related

How to quit scanner when input is negative?

This is the instructions.
Write a program that reads a sequence of input values and displays a bar chart of the values using asterisks. You may assume that all values are positive. First figure out the maximum value. That's value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.
This is what I came up so far. It's all good except I need to enter a letter instead of a negative number to quit scanning. I have tried (if( < 0) things) but those didn't work.
import java.util.Scanner;
public class BarChart1 {
public static void main(String [] args) {
int[] arr = new int[100];
int currentSize = 0;
System.out.println("Enter a sequence of positive integers. "
+ ("Enter a negative value to quit:"));
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0) {
break;
}
else {
arr[currentSize] = in.nextInt();
currentSize++;
}
}
//will find the max
double max = arr[0];
int y = 0;
for (int i = 1; i < arr.length; i++) {
y = i + 1;
if(max < arr[i]) {
max = arr[i];
//y = i + 1;
}
}
System.out.println("Max number is: " + max);
System.out.println("Number of digits = " + y);
System.out.println(Math.abs(-1));
double scale = 40/max;
System.out.println("Scale = " + scale);
for (int i = 0; i < y; i++) {
double h = scale * arr[i];
if (h != 0) {
for (int j = 1; j <= h; j ++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
This is the result.
1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************
I only need the asterisks. Everything else that is being printed is just for checking purposes.
You can try this:
while(in.hasNextInt()) {
int num =in.nextInt();
if(num <0){
break;
}
else{
arr[currentSize] = num;
currentSize++;
}
}

ADAGAME4 Spoj Wrong Answer

Below is a Archive PROBLEM from SPOJ. Sample testCase is passing, but I am getting W/A on submission. I am missing some testCase(testCases). Need help to figure out what case I am missing and/or what I am doing wrong here.
Ada the Ladybug is playing Game of Divisors against her friend Velvet Mite Vinit. The game has following rules. There is a pile of N stones between them. The player who's on move can pick at least 1 an at most σ(N) stones (where σ(N) stands for number of divisors of N). Obviously, N changes after each move. The one who won't get any stones (N == 0) loses.
As Ada the Ladybug is a lady, so she moves first. Can you decide who will be the winner? Assume that both players play optimally.
Input
The first line of input will contain 1 ≤ T ≤ 10^5, the number of test-cases.
The next T lines will contain 1 ≤ N ≤ 2*10^7, the number of stones which are initially in pile.
Output
Output the name of winner, so either "Ada" or "Vinit".
Sample Input:
8
1
3
5
6
11
1000001
1000000
29
Sample Output:
Ada
Vinit
Ada
Ada
Vinit
Vinit
Ada
Ada
CODE
import java.io.*;
public class Main
{
public static int max_size = 2 * (int)Math.pow(10,7) + 1;
//public static int max_size = 25;
//public static int max_size = 2 * (int)Math.pow(10,6) + 1;
public static boolean[] dp = new boolean[max_size];
public static int[] lastPrimeDivisor = new int[max_size];
public static int[] numOfDivisors = new int[max_size];
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
preprocess();
int t = Integer.parseInt(br.readLine());
while(t > 0)
{
int n = Integer.parseInt(br.readLine());
if(dp[n] == true)
System.out.println("Ada");
else
System.out.println("Vinit");
t--;
}
}
public static void markLastPrimeDivisor()
{
for(int i = 0 ; i < max_size ; i++)
{
lastPrimeDivisor[i] = 1;
}
for(int i = 2 ; i < max_size ; i += 2)
{
lastPrimeDivisor[i] = 2;
}
int o = (int)Math.sqrt(max_size);
for(int i = 3 ; i < max_size; i++)
{
if(lastPrimeDivisor[i] != 1)
{
continue;
}
lastPrimeDivisor[i] = i;
if(i <= o)
{
for(int j = i * i ; j < max_size ; j += 2 * i)
{
lastPrimeDivisor[j] = i;
}
}
}
/*for(int i = 1 ; i < max_size ; i++)
System.out.println("last prime of " + i + " is " + lastPrimeDivisor[i]);*/
}
public static void countDivisors(int num)
{
int original = num;
int result = 1;
int currDivisorCount = 1;
int currDivisor = lastPrimeDivisor[num];
int nextDivisor;
while(currDivisor != 1)
{
num = num / currDivisor;
nextDivisor = lastPrimeDivisor[num];
if(nextDivisor == currDivisor)
{
currDivisorCount++;
}
else
{
result = result * (currDivisorCount + 1);
currDivisorCount = 1;
currDivisor = nextDivisor;
}
}
if(num != 1)
{
result = result * (currDivisorCount + 1);
}
//System.out.println("result for num : " + original + ", " + result);
numOfDivisors[original] = result;
}
public static void countAllDivisors()
{
markLastPrimeDivisor();
for(int i = 2 ; i < max_size ; i++)
{
countDivisors(i);
//System.out.println("num of divisors of " + i + " = " + numOfDivisors[i]);
}
}
public static void preprocess()
{
countAllDivisors();
dp[0] = dp[1] = dp[2] = true;
for(int i = 3 ; i < max_size ; i++)
{
int flag = 0;
int limit = numOfDivisors[i];
//If for any i - j, we get false,for playing optimally
//the current opponent will choose to take j stones out of the
//pile as for i - j stones, the other player is not winning.
for(int j = 1 ; j <= limit; j++)
{
if(dp[i - j] == false)
{
dp[i] = true;
flag = 1;
break;
}
}
if(flag == 0)
dp[i] = false;
}
}
}
There is a subtle bug in your countDivisors() function. It assumes
that lastPrimeDivisor[num] – as the name indicates – returns the
largest prime factor of the given argument.
However, that is not the case. For example, lastPrimeDivisor[num] = 2
for all even numbers, or lastPrimeDivisor[7 * 89] = 7.
The reason is that in
public static void markLastPrimeDivisor()
{
// ...
for(int i = 3 ; i < max_size; i++)
{
// ...
if(i <= o)
{
for(int j = i * i ; j < max_size ; j += 2 * i)
{
lastPrimeDivisor[j] = i;
}
}
}
}
only array elements starting at i * i are updated.
So lastPrimeDivisor[num] is in fact some prime divisor of num, but not
necessarily the largest. As a consequence, numOfDivisors[55447] is computed
as 8 instead of the correct value 6.
Therefore in countDivisors(), the exponent of a prime factor in num
must be determined explicitly by repeated division.
Then you can use that the divisors function is multiplicative. This leads to
the following implementation:
public static void countAllDivisors() {
// Fill the `somePrimeDivisor` array:
computePrimeDivisors();
numOfDivisors[1] = 1;
for (int num = 2 ; num < max_size ; num++) {
int divisor = somePrimeDivisor[num];
if (divisor == num) {
// `num` is a prime
numOfDivisors[num] = 2;
} else {
int n = num / divisor;
int count = 1;
while (n % divisor == 0) {
count++;
n /= divisor;
}
// `divisor^count` contributes to `count + 1` in the number of divisors,
// now use multiplicative property:
numOfDivisors[num] = (count + 1) * numOfDivisors[n];
}
}
}

Adding and subtracting string numbers in Java

I'm supposed to create a program where a user enters two numbers that could be negative or positive and could contain decimal places or not. Theoretically, when you add say "256.78 + 78.6783" it is supposed to carry the one like a normal addition problem and finish the operation.
I have figured out how to add numbers of any length only when they are positive which took me FOREVER, but when I add negative numbers or even subtract the number I don't get the correct result. This is supposed to work with any set of two numbers that a user enters.
Here is my code so far, any suggestions?
P.S. I'm NOT allowed to convert these numbers to int's or double's before the operation so Parsing them is out of the question.
public class Number {
static Scanner kbd = new Scanner (System.in);
private String sign;
private String whole;
private String decimal;
private String fraction;
private static double firstNumber;
private static double secondNumber;
public static void main(String[] args) {
System.out.println("Please enter the first number: ");
firstNumber = kbd.nextDouble();
System.out.println("Next, enter the second number: ");
secondNumber = kbd.nextDouble();
Number x = new Number (firstNumber);
Number y = new Number (secondNumber);
Number sum = x.add(y);
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x + y = " + sum);
Number subtract = x.subtract(y);
System.out.println("x - y = " + subtract);
}
public Number()
{
whole = "0";
decimal = "0";
sign = "+";
}
public String toString()
{
return sign + whole + "." + decimal;
}
public Number (double n)
{
whole = "0";
decimal = "0";
sign = "+";
String numString = new Double(n).toString();
if (numString.charAt(0) == '-') {
sign ="-";
numString = numString.substring(1);
}
int position = numString.indexOf(".");
if (position == -1)
whole = numString;
else
{
whole = numString.substring(0,position);
decimal = numString.substring(position+1);
fraction = "";
}
}
public Number add (Number RHS) {
this.fixWhole (RHS);
this.fixDecimal(RHS);
return this.addNum (RHS);
}
public Number subtract (Number RHS) {
this.fixWhole(RHS);
this.fixDecimal(RHS);
return this.subtractNum (RHS);
}
private void fixWhole (Number RHS) {
int firstWholeNum = this.whole.length();
int secondWholeNum = RHS.whole.length();
int difference = firstWholeNum - secondWholeNum;
if (difference > 0) {
for (int i = 1; i <= difference; i++)
RHS.whole = "0" + RHS.whole;
}
else if (difference < 0 ) {
difference = Math.abs(difference);
for (int i = 1; i <= difference; i++)
this.whole = "0" + this.whole;
}
}
private void fixDecimal (Number RHS ) {
int firstDecimalNum = this.decimal.length();
int secondDecimalNum = RHS.decimal.length();
int difference = firstDecimalNum - secondDecimalNum;
if (difference > 0) {
for (int i = 1; i <= difference; i++)
RHS.decimal = RHS.decimal + "0";
}
else if (difference < 0 )
{
difference = Math.abs(difference);
for (int i = 1; i <= difference; i ++)
this.decimal = this.decimal + "0";
}
}
private Number addNum (Number RHS ) {
Number sum = new Number();
sum.decimal = "";
int carry = 0;
int decimalNum = this.decimal.length();
for (int i = decimalNum - 1; i >= 0; i --) {
char c1 = this.decimal.charAt(i);
char c2 = RHS.decimal.charAt(i);
int tempSum= (c1 - 48) + (c2 - 48) + carry;
carry = tempSum/ 10;
int sumDigit = tempSum % 10;
sum.decimal = (char) (sumDigit + 48) + sum.decimal;
}
sum.whole = "";
int wholeNum = this.whole.length();
for (int i = wholeNum - 1; i >= 0; i --) {
char c1 = this.whole.charAt(i);
char c2 = RHS.whole.charAt(i);
int tempSum = (c1 - 48) + (c2 - 48 ) + carry;
carry = tempSum / 10;
int sumDigit = tempSum % 10;
sum.whole = (char) (sumDigit + 48) + sum.whole;
}
if (carry != 0)
sum.whole = "1" + sum.whole;
return sum;
}
private Number subtractNum (Number RHS ) {
Number sum = new Number();
sum.decimal = "";
int carry = 0;
int decimalNum = this.decimal.length();
for (int i = decimalNum - 1; i >= 0; i --) {
char c1 = this.decimal.charAt(i);
char c2 = RHS.decimal.charAt(i);
int tempSum= (c1 - 48) - (c2 - 48) - carry;
carry = tempSum/ 10;
int sumDigit = tempSum % 10;
sum.decimal = (char) (sumDigit - 48) + sum.decimal;
}
sum.whole = "";
int wholeNum = this.whole.length();
for (int i = wholeNum - 1; i >= 0; i --) {
char c1 = this.whole.charAt(i);
char c2 = RHS.whole.charAt(i);
int tempSum = (c1 - 48) - (c2 - 48 ) + carry;
carry = tempSum / 10;
int sumDigit = tempSum % 10;
sum.whole = (char) (sumDigit + 48) + sum.whole;
}
if (carry != 0)
sum.whole = "1" + sum.whole;
return sum;
}
}
take both the numbers as strings and store the signs into the sign string into the corresponding Numbers objects and call your method like
System.out.println("Please enter the first number: ");
firstNumber = kbd.nextString();
System.out.println("Next, enter the second number: ");
secondNumber = kbd.nextString();
Number x = new Number (firstNumber.substring(1),firstNumber.charAt(0));
Number y = new Number (secondNumber.substring(1),secondNumber.charAt(0));
/*convert the firstNumber.substring(1) and secondNumber.substring(1) to doubles using Double.parseDouble()*/
public String doTheOperation(Number other){
if(this.sign.equals(otherNumber.sign)){
/*simply the double values and put the sign*/ in front of it and return it
}
else{
do the simple double subtraction and by looking at your code i believe you can find out the bigger double among them
}
}

adding and subtracting strings in Java

I need some help on a program i'm supposed to create. i'm supposed to create a program that reads two strings of any length that are user inputted and it subtracts or adds them together. i'm NOT allowed to convert these strings into numbers before the operation. this is what I got so far.My teacher mentioned something like converting the strings into uni-code to add and subtract them but i have no idea how to do it as we haven't even learned uni-code. HERE IS MY CODE:
import java.util.Scanner;
public class Number {
private char Sign;
private String Whole;
private String Fraction;
public static void main(String[] args) {
Scanner Keyboard = new Scanner (System.in);
System.out.println("This program adds or subtracts numbers of any lengths, please add two numbers: ");
String num1 = Keyboard.nextLine();
System.out.println("Enter the second number: ");
String num2 = Keyboard.nextLine();
String sum = " ";
int length = num1.length();
int carry = 0;
public Number Add(Number RHS) {
for (int i = length -1 ; i >= 0; i--) {
char c1 = num1.charAt(i);
char c2 = num2.charAt(i);
int tempSum = (c1 - 48) + (c2 - 48) + carry;
carry = tempSum / 10;
int sumDigit = tempSum % 10;
sum = (char) (sumDigit + 48) + sum;
if (carry == 1) {
sum = "1" + sum;
}
}
}
}
public Number (double n) {
Whole = " ";
Fraction = " ";
if (n >= 0) {
Sign = '+';
}
else
{
Sign = '-';
n = Math.abs(n);
String numString = new Double(n).toString();
int position = numString.indexOf(".");
}
}
}
public static String add(String as, String bs){
ArrayList<String> BigNum = new ArrayList<>();
int m = as.length()-1;
int n = bs.length()-1;
int min = m > n ? n : m ;
int max = 0;
String s;
if(n > m){
s = bs;
max = n;
}else{s = as ; max = m;}
Integer carry = 0;
while(true){
int a = Integer.parseInt(Character.toString(as.charAt(m)));
int b = Integer.parseInt(Character.toString(bs.charAt(n)));
Integer c = a + b + carry;
if(c > 9){
carry = 1;
c %=10;
}else carry = 0;
BigNum.add(c.toString());
n--; m--; min--; max--;
if ( min < 0 ) {
if(carry !=0 && max < 0 )
BigNum.add(carry.toString());
break;
}
}
Integer c = carry;
while(max >= 0) {
c += Integer.parseInt(Character.toString(s.charAt(max)));
BigNum.add(c.toString());
c = 0;
max--;
}
String s2 = "";
for (int i = BigNum.size()-1; i >= 0; i--) {
s2 +=BigNum.get(i);
}
return s2;
}

trying to find the sum of even fibonacci numbers to 4 million

I am trying to find the sum of the even Fibonacci numbers up untill 4 million.
I found the numbers but i can't get them add up... in the if(n % 2 ==0) loop
8
34
144
610
2584
10946
46368
196418
832040
3524578
public static void number2()
{
int number = 40;
int a, b, c;
int numLim = 0;
a = 1;
b = 2;
while(numLim < 4000000)
{
c = a + b;
a = b;
b = c;
numLim = b;
if(numLim > 4000000)
{
break;
}
int sum = 0;
if(numLim % 2 == 0)
{
System.out.println(numLim);
sum = sum + numLim;
System.out.println("sum :" +sum);
}
}
}
You must define sum outside the while loop, or it will become 0 each iteration.
int sum = 0;
...
while ...
Remember not to set sum to 0 each iteration.
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 32; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
sum += fibonacci;
System.out.println("This is the sum " +sum);
}
}
}
So I solved it like this, it's a little more efficient and the math works but Euler hates me, hope this helps.
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 31; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
if (fibonacci%2 == 0) {
sum += fibonacci;
System.out.println(sum);
}
}
}
Sorry, this code works.
Tried doing the above in Java and here is my solution that works
public static void main(String[] args) {
int first = 1;
int second = 2;
int sum = 0;
int sumOfEvenValuedTerms = second;
for (int i = 0; i < 30; i++) {
sum = first + second;
if (sum <= 4000000) {
if (sum % 2 == 0) {
sumOfEvenValuedTerms += sum;
}
first = second;
second = sum;
}
}
System.out.println(sumOfEvenValuedTerms);
}
Output is 4613732
public static int getSumOfEvenNumbers(int n) {
int prev = 0;
int i =1;
int sum = 0;
while (i<n){
int nextNumber = i + prev;
if(nextNumber %2 ==0) {
System.out.println(nextNumber);
sum +=nextNumber;
}
prev = i;
i = nextNumber;
}
return sum;
}
public class evenFib {
public static void main(String[] args) {
double a = 1, b = 2, c = 0, sum = 0;
for (double i = 0; i <= 1000; i++) {
c = a + b;
a = b;
b = c;
if (c % 2 == 0 && sum < 4000000) {
sum = sum + c;
}
}
System.out.println(sum + 2);
}
}

Categories

Resources