Maximum Remainder - java

Maximum remainder
You are given a number N. Write a program to find a natural number that is smaller than N such that N gives the highest remainder when divided by that number.
If there is more than one such number, print the smallest one.
Can anyone help I think I'm missing something like if 2 numbers will have same reaminders my code would overwrite the minDivisor to the upper value
static int findRemainder(int num){
int maxRemainder=0;
int minDivisor=0
int answer=0;
for(int i = 1; i<num; i++){
if(maxRemainder <= (num % i)) {
maxRemainder = num % i;
if(minDivisor < i && maxRemainder == num%i) {
} else {
minDivisor = i;
}
}
return minDivisor;
}
}

Check this out:
int largestRemainder = c % ((c/2) + 1);

Related

Armstrong Number Checker in Java

I am still somewhat of a beginner to Java, but I need help with my code. I wanted to write an Armstrong Number checker.
An Armstrong number is one whose sum of digits raised to the power three equals the number itself. 371, for example, is an Armstrong number because 3^3 + 7^3 + 1^3 = 371.
If I understand this concept correctly, then my code should work fine, but I don't know where I made mistakes. I would appreciate if you could help correct my mistakes, but still kind of stick with my solution to the problem, unless my try is completely wrong or most of it needs to change.
Here is the code:
public class ArmstrongChecker {
boolean confirm = false;
Integer input;
String converter;
int indices;
int result = 1;
void ArmstrongCheck(Integer input) {
this.input = input;
converter = input.toString();
char[] array = converter.toCharArray();
indices = array.length;
result = (int) Math.pow(array[0], indices);
for (int i = 1; i < array.length; i++) {
result = result + (int) Math.pow(array[i], indices);
}
if (result == input) {
confirm = true;
System.out.println(confirm);
} else {
System.out.println(confirm);
}
}
}
For my tries I used '153' as an input. Thank you for your help!
You aren't summing the digits, but the numeric values of the characters representing them. You can convert such a character to its numeric value by subtracting the character '0':
int result = 0;
for(int i = 0; i < array.length; i++) {
result = result + (int) Math.pow(array[i] - '0', indices);
}
Having said that, it's arguably (probably?) more elegant to read the input as an actual int number and iterate its digits by taking the reminder of 10 on each iteration. The number of digits itself can be calculated using a base-10 log.
int temp = input;
int result = 0;
int indices = (int) Math.log10(input) + 1;
while (temp != 0) {
int digit = temp % 10;
result += (int) Math.pow(digit, indices);
temp /= 10;
}
There is a small logical mistake in your code, You're not converting the character to an integer instead you're doing something like
Math.pow('1', 3) -> Math.pow(49, 3) // what you're doing
Math.pow(1, 3) // what should be done
You should first convert the character to the string using any method below
result = (int) Math.pow(array[0],indices);
for(int i = 1;i<array.length;i++) {
result = result + (int) Math.pow(array[i],indices);
}
For converting char to integer
int x = Character.getNumericValue(array[i]);
or
int x = Integer.parseInt(String.valueOf(array[i]));
or
int x = array[i] - '0';
Alternatively
You can also check for Armstrong's number without any conversion, using the logic below
public class Armstrong {
public static void main(String[] args) {
int number = 153, num, rem, res = 0;
num = number;
while (num != 0)
{
rem = num % 10;
res += Math.pow(rem, 3);
num /= 10;
}
if(res == num)
System.out.println("YES");
else
System.out.println("NO");
}
}
For any int >= 0 you can do it like this.
Print all the Armstrong numbers less than 10_000.
for (int i = 0; i < 10_000; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
prints
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
The key is to use Math.log10 to compute the number of digits in the candidate number. This must be amended by adding 1. So Math.log10(923) returns 2.965201701025912. Casting to an int and adding 1 would be 3 digits.
The number of digits is then the power used for computation.
Then it's just a matter of summing up the digits raised to that power. The method short circuits and returns false if the sum exceeds the number before all the digits are processed.
public static boolean isArmstrong(int v) {
if (v < 0) {
throw new IllegalArgumentException("Argument must >= 0");
}
int temp = v;
int power = (int)Math.log10(temp)+1;
int sum = 0;
while (temp > 0) {
sum += Math.pow(temp % 10, power);
if (sum > v) {
return false;
}
temp/= 10;
}
return v == sum;
}

find smallest number divisible by N with sum of digits as N

For a given number N(0<N<=100) find out the minimum positive integer X divisible by N, where the sum of digits of X is equal to N, and X is not equal to N.
public static int getSmallestNumber(int input1) {
int res =0;
for(int i=2;i<10000;i++) {
if(getSum(input1*i) == input1) {
res = input1*i;
break;
}
}
return res;
}
static int getSum(int n) {
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n/10;
}
return sum;
}
Example: Input: 9
output: 18
Explanation: 1+8 is 9 and 18 is divisible by 9
Example2: Input: 10
output: 190
Explanation: 1+9+0 is 10 and 190 is divisible by 10
My solution works for smaller integer but breaks for larger numbers like 98, 99 or 100.
we need to know that if we multiply multiple of 7, 35(3+5=8) with 7 again then obviously a larger number 42(4+2=6) comes but have lower sum of digits so the change in digits with each multiplication seems uncertain. So, if we can find a way to generalize this change in digits of upcoming next to next larger multiples of our number then a time efficient solution can be designed.
I think you need to add the actual check on the condition (i % input1 == 0) to check the divisibility.
public static int getSmallestNumber (int input1) {
int res = 0;
for (int i = input1; i < 10000; i++) {
if (getSum(i) == input1 && i % input1 == 0) {
res = i;
break;
}
}
return res;
}
static int getSum (int n) {
int sum = 0;
while (n != 0) {
sum = sum + n % 10;
n = n/10;
}
return sum;
}

Java program on "friendly numbers "

I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.
Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.
import java.util.Scanner;
public class A5E4 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter an integer: ");
int friendlyNumber = in.nextInt();
boolean result = isFriendly(friendlyNumber);
if (result)
{
System.out.println("The integer is friendly");
}
else
{
System.out.println("The integer is not friendly");
}
}
public static boolean isFriendly(int number)
{
int counter = 1;
while (number / 10 >= 1)
{
counter ++;
number = number / 10;
}
boolean check = true;
for (int i = 1; i <= counter; i++)
{
if (number / Math.pow(10, (counter - i)) % i == 0 && check)
{
check = true;
}
else
{
check = false;
}
}
return check;
}
}
while (number / 10 >= 1){
counter ++;
number = number / 10;
}
In this bit, you are reducing number to something smaller than 10. That is probably not what you want. You should make a copy of number here.
Also, proper software design would recommend that you extract this to a dedicated method.
private int countDigits(int number){
if(number < 1) throw new IllegalArgumentException();
int n = number;
int counter = 1;
while (n / 10 >= 1){
counter ++;
n = n / 10;
}
return counter;
}
You need to copy the number which you use to find out how much digits your number has. Otherwise you change the number itself and don't know anymore what it was.
The second mistake is that you divide an integer by Math.pow() which returns a double. So your result is double. You want to have an integer to use the modulo operator.
public static boolean isFriendly(int number)
{
int counter = 1;
int tmpNumber = number;
while (tmpNumber / 10 >= 1)
{
counter ++;
tmpNumber = tmpNumber / 10;
}
boolean check = true;
for (int i = 1; i <= counter; i++)
{
if ((int)(number / Math.pow(10, (counter - i))) % i == 0 && check)
{
check = true;
}
else
{
check = false;
}
}
return check;
}
The first problem is that you are modifying the value of the number you are trying to check. So, if your method is called with 149, then after the while loop to count the digits, its value will be 1. So, you are always going to find that it is 'unfriendly'. Assuming you fix this so that number contains the number you are checking. Try this instead of your 'for' loop:
while ( counter && !( ( number % 10 / counter ) % counter ) )
{
number = number / 10;
counter--;
}
It works by taking the last digit of your number using the modulus or remainder operator and then divides this by the digit position and checks that the remainder is zero. If all is good, it decrements the counter until it reaches zero, otherwise it terminates before counter is zero.
Try something like this (change your isFriendly() method):
public static boolean isFriendly(int number)
{
String numberAsString = String.valueOf(number); //Convert the int as a String to make it easier to iterate through
for(int i = 0; i < numberAsString.length(); i++) {
int currentDigit = Character.getNumericValue(numberAsString.charAt(numberAsString.length() - i - 1)); //Iterate over the number backwards
System.out.println(currentDigit); //Print the current digit
if(currentDigit % (i + 1) != 0) {
return false;
}
}
return true;
}
The easy way is to convert to string and then check if it is friendly:
public static boolean isFriendly(int number)
{
String num = Integer.toString(number);
for (int i = 0, dividedBy = 1; i < num.length(); i++, dividedBy++)
{
String numToCheck = "";
for (int j = 0; j <= i; j++)
{
numToCheck += num.charAt(j);
}
if (Integer.valueOf(numToCheck) % dividedBy != 0) {
return false;
}
}
return true;
}

Multiples Program

Here is the programming problem i am trying to solve: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Here is my solution so far, however the answer comes up as zero everytime so i think i have an error in my code. Any help would be appreciated.
public static boolean isDiv(int num){
boolean isDiv = false;
for (int i = 1; i <= 20; i++){
if (i == 20){
isDiv = true;
}
if ((num % i) == 0){
continue;
}
else {
break;
}
}
return isDiv;}
public static int smallMulti(int num){
boolean div = isDiv(num);
int answer = 0;
for (int i = num; num < 2520; i--){
if (div = true){
answer = i;
}
}
return answer;}
You are overcomplicating the whole problem, combined with multiple logical mistakes. Basicly you just need 2 loops. Here´s a the code checking for the first number beeing devisible by every number until Integer.MAX_VALUE. If you want to go higher you could adopt the code to work with long.
public static int smallMulti(int num) {
for (int i = 1; num <= Integer.MAX_VALUE; ++i) { // Check every int in the scope of the Integer
for (int j = 2;j<=num;++j) {
if(i % j != 0) {
break; // If i % j is unequal to 0 then this number isn´t valid.
}
if(j == num) {
return i; // If we reached j == num then everything was divisble yet so we can return i as the correct value;
}
}
}
return -1;
}
Heres the example output for this main
public static void main(String[] args) {
for(int i = 2; i <= 20; ++i)
System.out.println("Smallest Value divisible by 1-"+ i + " = " + smallMulti(i));
}
OutPut
Smallest Value divisible by 1-2 = 2
Smallest Value divisible by 1-3 = 6
Smallest Value divisible by 1-4 = 12
Smallest Value divisible by 1-5 = 60
Smallest Value divisible by 1-6 = 60
Smallest Value divisible by 1-7 = 420
Smallest Value divisible by 1-8 = 840
Smallest Value divisible by 1-9 = 2520
Smallest Value divisible by 1-10 = 2520
Smallest Value divisible by 1-11 = 27720
Smallest Value divisible by 1-12 = 27720
Smallest Value divisible by 1-13 = 360360
Smallest Value divisible by 1-14 = 360360
Smallest Value divisible by 1-15 = 360360
Smallest Value divisible by 1-16 = 720720
Smallest Value divisible by 1-17 = 12252240
Smallest Value divisible by 1-18 = 12252240
Smallest Value divisible by 1-19 = 232792560
Smallest Value divisible by 1-20 = 232792560
I implemented with lcm(least common multiple)
public static int lcm(int a, int b) {
return (a*b)/gcd(a, b);
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int smallMulti(int n) {
int number = 1;
for (int i = 2; i <= n; i++) {
number = lcm(number, i);
}
return number;
}

How to calculate the average of even and odd numbers in an array?

As a class exercise I have to code using methods a program that:
1) Calculates the average of even and odd numbers in an array.
I expect on using one method to find the average of even and odd numbers. However, I'm having trouble on returning the right average. For example, if I enter only odd numbers I get an error, and vice versa.
This error:
"java.lang.ArithmeticException: / zero"
Also, if it were possible I would like to get some help on coding the rest of the exercise which asks for:
2) Print the highest and lowest number in the array
3) Allow the user to modify any of the numbers of the array
So far I have this code:
public static void main (String args[]){
int x[] = new int[4];
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length ; i++){
System.out.println("Enter a number: ");
x[i] = input.nextInt();
}
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
}
public static int getAverage(int a[]){
int add_even = 0;
int counter_even = 0;
int average_even = 0;
int add_odd = 0;
int counter_odd = 0;
int average_odd = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0){
add_even += a[i];
counter_even++;
}
else if(a[i] % 2 == 1) {
add_odd += a[i];
counter_odd++;
}
}
if (add_even % 2 == 1 && add_odd % 2 == 1){
average_even = 0;
average_odd = add_odd / counter_odd;
return average_even;
}
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
else{
average_even = 0;
average_odd = add_odd / counter_odd;
return average_odd;
}
}
Thank you!
Your get average looks more complicated then it needs to be.
First off the getAverage(x):
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
will return the same value, so if you wanted to get the average for odds or evens the method should require a boolean arg to represent odd or even.
In your method you should loop through all the numbers and check if it is even. If it is even and you are averaging evens add it to a "total" and add one to a counter. At the end divide "total" by the counter and return the value. The average will most likely include a decimal value, so you should return a double or a float.
Example:
public static double getAverage(int a[], boolean even){
double total = 0;//These are doubles so dividing later does not require casting to retain a decimal (this can be an int if you only want to return integers)
double counter = 0;
for(int i = 0; i<a.length; i++){
if(a[i] % 2 == 0 && even){//even
counter++;
total += a[i];
}else{//odd
counter++;
total += a[i];
}
}
if(total == 0){//Avoid dividing by 0.
return 0; //You can also throw an exception instead of returning 0.
}
return total / counter; //Returns the average for even or odd numbers.
}
For the second part of your question you need to loop through the numbers and find the highest and lowest while looping.
Example:
int highest = 0;
int lowest = 0;
for(int i = 0; i<x.length; i++){
if(x[i] > highest){
highest = x[i];
}
if(x[i] < lowest){
lowest = x[i];
}
if(i == 0){
highest = x[i];
lowest = x[i];
}
}
You have a divide by zero error cropping up here.
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
0 % 2 == 0 so even if add_even is 0 (and as a result, so is counter_even) you're attempting to use it to divide. You'll need to account for that in your code by checking if counter_even is 0.
else if (counter_even != 0 && add_even % 2 == 0 && add_odd % 2 == 0){
1)Using one method to get the average of the even and odd numbers isn't proper because you only return one int. It would be simpler to use two methods but if you're insistent on using one method you could add a boolean as a parameter like this to decide which to do. To handle the ArithmeticException just return 0 if there are no values.
public static int average(int[] n, boolean even) {
int total = 0;
int count = 0;
for (int i = 0; i < n.length; i++) {
if (even == (n % 2 == 0)) {
total += n;
count ++;
}
}
if (count == 0)
return 0;
return total / count;
2)To check find the max and min value simply loop through the array like this
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
if (x[i] < min)
min = x[i];
if (x[i] > max)
max = x[i];
}
3)To allow the user to modify the array, you could print the values and prompt them as to which value they would like to change like this.
System.out.print("Array: ");
for (int i = 0; i < x.length; i++) {
System.out.print(i + ",");
}
System.out.println();
System.out.println("Which value would you like to change?");
int index = input.nextInt();
System.out.println("What do you want the new value to be?");
int value = input.nextInt();
You can then run a method that changes the value of the array
edit(x, index, value);
public static int edit(int[] n, int index, int value) {
n[index] = value;
return n;
}
I used JS for this task, you can just rewrite my code to Java language.
A number is divisible by 2 if the result of its division by 2 has no
remainder or fractional component - in other terms if the result is an
integer. Zero is an even number because when 0 is divided by
2, the resulting quotient turns out to also be 0 - an integer (as a
whole number that can be written without a remainder, 0 classifies as
an integer).
function compareEvenOddAverage(arr) {
let even = 0,
odd = 0,
evenCounter = 0,
oddCounter = 0,
str = '';
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
even += arr[i];
evenCounter++;
} else {
odd += arr[i];
oddCounter++;
}
}
if (even / evenCounter > odd / oddCounter) {
str += 'Average value of even numbers is greater';
} else if (even / evenCounter < odd / oddCounter) {
str += 'Average value of odd numbers is greater';
} else {
str += 'Average values are equal';
}
return str;
}
console.log(compareEvenOddAverage([0, 1, 2, 3, 4, 5]));

Categories