quotient and remainder without division and modulo operators - java

I've been working on this problem for the past two hours or so and I've encountered a roadblock. I can actually perform the division but when it comes time to print the remainder that isn't 0 the output doesn't match. I would like to know what is it what I'm doing wrong.
public class Division {
public static void main(String[] args) {
int numerator = 0;
int numeratorprint = 0;
int denominator = 0;
int product = 0;
int remainder = 0;
int counter = 1;
Scanner input;
input = new Scanner(System.in);
System.out.print("Enter two positive intergers for division:\n");
numerator = input.nextInt();
numeratorprint = numerator;
denominator = input.nextInt();
while ((numerator < 0) || (denominator < 0)) {
System.out.print("Enter two positive intergers for division:\n");
numerator = input.nextInt();
denominator = input.nextInt();
}
if (numerator == 0){
System.out.print(numerator + "/" + denominator + " = " + numerator + " with a remainder of " + numerator);
}
else if (denominator == 0){
System.out.print("This result is undefined (Cannot divide by Zero)");
}
else if (denominator > numerator){
System.out.print("Cannot do proper fractions");
}
else {
while (numerator > denominator){
counter++;
numerator = numerator - denominator;
}
}
product = counter * denominator;
remainder = numeratorprint - product;
System.out.println(numeratorprint + " / " + denominator + " = " + counter + " with a remainder of " + remainder);
}
}
/* Sample I/O 1
Enter two positive intergers for division:
25
5
OUTPUT:
25 / 5 = 5 with a remainder of 0
Sample I/O 2
Enter two positive intergers for division:
27
5
OUTPUT:
27 / 5 = 6 with a remainder of -3
*/

I believe you have an off by one error where you are starting your counter at 1 rather than 0. I tested a few numbers and changing this seems to fix it just fine. So change
int counter = 1;
to
int counter = 0;
Also, you must change your while loop conditional on the else block to be
while (numerator >= denominator) {...
in order to account for the case of when the divisor evenly divides the dividend.

I saw few errors in your code.
1. Redundant variable
2 why don`t you use modular operator ?
3. you can remove a while loop too
public class Division {
public static void main(String[] args) {
Scanner input;
input = new Scanner(System.in);
System.out.print("Enter two positive intergers for division:\n");
int numerator = input.nextInt();
int numeratorprint = numerator;
int denominator = input.nextInt();
int quotient = 0;
int remainder = 0;
while ((numerator < 0) || (denominator < 0)) {
System.out.print("Enter two positive intergers for division:\n");
numerator = input.nextInt();
denominator = input.nextInt();
}
if (numerator == 0) {
System.out.print(numerator + "/" + denominator + " = " + numerator + " with a remainder of " + numerator);
} else {
if (denominator == 0) {
System.out.print("This result is undefined (Cannot divide by Zero)");
} else {
if (denominator > numerator) {
System.out.print("Cannot do proper fractions");
} else {
remainder = numerator % denominator;
quotient = ((numerator / denominator) - (remainder / denominator));
}
}
}
System.out.println(numeratorprint + " / " + denominator + " = " + quotient + " with a remainder of " + remainder);
}
}

Related

Java code finds Armstrong number upto 3 digit numbers but fails on 4 digit onwards

I just started learning java 2 days ago and tried doing an assignment to find if the three digit number was an Armstrong number or not. This code works upto 3 digit numbers and after that it fails to work on 4 digit Armstrong numbers like 1634, 8208 etc..
public class project1 {
public static void main(String[] args) {
int number = 9474, 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.");
}
}
Your solution just support 3 digit numbers. If you want to change it for numbers with any digits should first count number of digits:
int numberOfDigits = 0;
while (originalNumber != 0) {
numberOfDigits++;
originalNumber /= 10;
}
And then just a minor changes in your code for power of Math.pow method as:
result += Math.pow(remainder, numberOfDigits);
The complete solution is:
class project1 {
public static void main(String[] args) {
int number = 9474, originalNumber, remainder, result = 0;
originalNumber = number;
int numberOfDigits = 0;
while (originalNumber != 0) {
numberOfDigits++;
originalNumber /= 10;
}
originalNumber = number;
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, numberOfDigits);
originalNumber /= 10;
}
if (result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
public class ArmstrongNumberDemo
{
public static void main(String[] args) {
int num = 9474, realNumber, remainder, output = 0, a = 0;
realNumber = num;
for(;realNumber != 0; realNumber /= 10, ++a);
realNumber = num;
for(;realNumber != 0; realNumber /= 10){
remainder = realNumber % 10;
output += Math.pow(remainder, a);
}
if(output == num){
System.out.println(num + " is an Armstrong number.");
}
else{
System.out.println(num + " is not an Armstrong number.");
}
}
}

Odd sum application not calculating negative integers correctly?

I'm supposed to create an application that takes a number from the user in order to create a range from 1 to the number that the user enters. I then need to calculate the sum of all odd numbers between 1 and the number that the user enters. This works fine with positive integers but not with negative?
import java.util.Scanner;
public class OddSumApplication {
public static void main (String[]args){
int sum = 0;
System.out.print("Enter a positive or negative integer: ");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
if (num == 1){
System.out.println(num);
System.out.println("Sum = " + num);
}
else{
while (num != 1){
if (num >= 1){
if (num % 2 == 1){
sum = sum + num;
num = num - 2;
}
else{
num = num - 1;
}
}
else{
if (num % 2 == 1){
sum = sum + num;
num = num + 2;
}
else{
num = num + 1;
}
}
}
}
sum = sum + 1;
System.out.print("\nSum = " + sum);
}
}
It's because negative odd number % 2 returns negative one. Try to give it into absolute value.
...
if (Math.abs(num%2) == 1) {
sum = sum + num;
num = num + 2;
} else {
num = num + 1;
}
A good check to find a number is odd is to check if the remainder by dividing the number is not 0 rather then checking if it is 1. The method would look like:
public boolean isOdd(int number) {
return !(number % 2 == 0);
}

Programming a Luhn Algorithm in Java

I'm trying to program the Luhn Algorithm within Java.
My current code is :
import java.util.Scanner;
public class luhnAlgorithm {
public static void main(String[] args) {
System.out.println("main() : Entry Point");
Scanner input = new Scanner(System.in);
long num;
int digit;
int sum = 0;
System.out.println("Enter the digits of a credit card number : ");
num = input.nextLong();
while (num > 0) {
digit = (int) num % 10;
num = num / 10;
if (num % 2 != 0 ) {
digit *= 2;
}
if (digit > 9) {
digit -= 9;
}
sum += digit;
}
if(sum % 10 == 0) {
System.out.println("Credit card number is valid.");
}
else
System.out.println("Credit card number is invalid. Please try again.");
System.out.println("main() : Exit Point");
}
}
The problem I'm having is that when I enter in a valid credit card number, for example : 4012888888881881 (via PayPal Test Credit Card Accounts), it says it's invalid. But when I put in my own debit card number it says it's valid.
I know there's some code messed up in here, I just can't figure out what.
Any help would be appreciated and thanks in advance!
I think that I know where the problem is. You do the multiplication in a wrong way:
if (num % 2 != 0 ) {
digit *= 2;
}
You multiply digit when num is odd and in Luhn's algorithm you should multiply digit when this digit is on the even place in number moving from right to the left. Try to think about adding some index which will help you to know if a digit is on even place or not.
You can think about splitting your integer to array and then check if index of array is even or add to your while loop some index.
Carefully study this https://en.wikipedia.org/wiki/Luhn_algorithm
for example if you have 68 then you have: first iteration: digit = 8, num = 6 and sum =8 second iteration: digit = 6, num = 0 here you should multiply your digit by 2, because it is on the even place in number, but you don't do that and sum = 14 instead of 20
Okay I actually figured it out :).
import java.util.Scanner;
/*
* Author : Jonathan Patterson
* Date : 10/28/15
* Program : Luhn Algorithm; validates credit card numbers
*/
public class luhnAlgorithm {
public static void main(String[] args) {
System.out.println("main() : Entry Point");
Scanner input = new Scanner(System.in);
long num;
double digit = 0;
int sum = 0;
int n = 1;
int i = 0;
System.out.println("Enter the digits of a credit card number : ");
num = input.nextLong();
while (num > 0) {
digit = num % 10;
num = num / 10;
System.out.println(n + " digit is : " + digit);
if (i % 2 != 0 ) {
digit *= 2;
}
System.out.println(n + " digit is : " + digit);
if (digit > 9) {
digit = (digit % 10) + 1;
}
else
digit *= 1;
System.out.println(n + " digit is : " + digit);
sum += digit;
n++;
i++;
}
System.out.println("Sum of the digits is : " +sum);
if(sum % 10 == 0) {
System.out.println("Credit card number is valid.");
}
else
System.out.println("Credit card number is invalid. Please try again.");
System.out.println("main() : Exit Point");
}
}
Adding an additional answer to this in case anyone else finds this post.
There is a bitbucket project with a valid implementation:
https://bitbucket.org/javapda/npi-validator/src/master/
This if for verifying NPI provider numbers which is an implementation of the Luhn algorithm.
package org.bitbucket.javapda.npi;
import java.util.ArrayList;
import java.util.List;
public class NpiValidator {
private String npi;
public NpiValidator(String npi) {
this.npi = npi.trim();
}
public boolean isValid() {
return npi.length() == 10 && complies();
}
private boolean complies() {
if (!npi.matches("[0-9]{10}")) {
return false;
}
Character lastDigit = npi.charAt(9);
List<Integer> everyOther = listWithEveryOtherDoubled(npi.substring(0, 9));
int sum = 0;
for (Integer num : everyOther) {
sum += sumOfDigits(num);
}
int total = sum + 24; // 24 to account for 80840
int units = total % 10;
int checkDigit = (units != 0) ? (10 - units) : units;
return (Character.getNumericValue(lastDigit) == checkDigit);
}
private List<Integer> listWithEveryOtherDoubled(String str) {
List<Integer> nums = new ArrayList<Integer>();
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
nums.add(2 * Character.getNumericValue(str.charAt(i)));
} else {
nums.add(Character.getNumericValue(str.charAt(i)));
}
}
return nums;
}
private static int sumOfDigits(int number) {
int num = number;
int sum = 0;
while (num > 0) {
sum += (num % 10);
num = num / 10;
}
return sum;
}
public static void main(String[] args) {
System.out.println("Hello, World!");
// System.out.println(sumOfDigits(16));
System.out.println("1234567890".matches("[0-9]{10}"));
System.out.println("123456789".matches("[0-9]{10}"));
}
}

How can I get the total to be put into separate numbers, and add only the odd ones

import java.util.Scanner;
public class While
{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Choose a number to find various things for: ");
int n = in.nextInt();
// Extraneous variables to keep myself organized.
int i = 0;
int b = 1;
int t = 0;
int sum1 = 0;
int sum2 = 0;
double sum3 = 0;
double total = 0;
// Extraneous code to keep simple.
System.out.println("Squares up until your number");
while ( (i * i) < n ){
System.out.println(i * i);
sum1 = sum1 + (i * i);
i++;
}
System.out.println("Now positives divisible by 10");
while ( (b * 10) < n){
System.out.println(b * 10);
sum2 = sum2 + (b * 10);
b++;
}
System.out.println("Now squares of 2!");
while ( Math.pow(2,t) < n ){
System.out.println(Math.pow(2,t));
sum3 = sum3 + (Math.pow(2,t));
t++;
}
// Second part of assignment.
total = total + (sum1 + sum2 + sum3);
System.out.println("The sum of all numbers: " + total);
System.out.println();
}
}
Now, the total needs to be separated into its own numbers.
If the user puts in the number 50, the program's total will be 303.
How can I get that 303 to be, 3, 0, 3, then add only the odd numbers
then use a simple System.out. to print a 6 for this example?
Use modulus to get digit by digit. Check this answer to further explanation.
int sum = 0;
while (total > 0) {
int digit = (int) total % 10;
total = total / 10;
if (digit % 2 != 0) sum += digit;
}
System.out.println("The sum of all odd digits: " + sum);
System.out.println();
OUTPUT for 50:
The sum of all numbers: 303.0
The sum of all odd digits: 6
OUTPUT for 200:
The sum of all numbers: 3170.0
The sum of all odd digits: 11
int mod = 0, sum = 0;
while (total > 1) {
mod = (int) (total % 10);
total = total / 100;
sum += mod;
}
System.out.println("The sum of odd numbers is " + sum);
I have used the modulus operator to get the mod. But as you need odd numbers, I divided total by 100 till it is greater than 1. Lower number of loops will run in this case.

Having trouble with a while loop that gets a certain series of numbers from an input

I'm trying to half the input if it % 12 == 0, but if it isn't then you multiply it by 3 and add 1 onto the sum.
The question that I'm working off is: http://i.imgur.com/VzuPtZJ.png
With the code I have currently(which is below), if I enter 12, like in the question I start off with 6, but then the results begin to go wrong and then they go insanely wrong with values in the millions and negative millions etc.
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x >= 1)
{
if (x % 12 == 0)
x = x / 2;
else
x = 3 * x + 1;
count++;
results += + x + ", ";
if (x > max)
max = x;
}
results += "a total of " + count + " numbers in this sequence with a maximum value of " + max;
System.out.print(results);
}
}
The question says divide by two if the number is even. But you divide by 2 only when it is dividable by 12.
Change this line
(x % 12 == 0)
to
(x % 2 == 0)
And change while (x >= 1) to while (x > 1)
Here is the code you are looking for:-
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x > 1)
{
if (x % 2 == 0)
x = x / 2;
else
x = 3*x + 1;
System.out.print(x+" ");
max++;
}
}
}

Categories