What I am trying to do should be pretty easy, but as I'm new to java, I'm struggling with what might be basic programming.
The main issue is how to check if the (x+1) number of an integer is greater than the x number, which I am trying to do as follow :
for( int x=0; x < Integer.toString(numblist).length();x++) {
if (numblist[x] < numblist[x+1]) {
compliance= "OK";
} else{
compliance="NOK";
}
But it returns an error "array required but integer found".
It seems to be a basic type mistake, which might come from the previous step (keeping only the numbers included in a string):
for (int p = 0; p < listWithoutDuplicates.size(); p++) {
Integer numblist = Integer.parseInt(listWithoutDuplicates.get(p).getVariantString().replaceAll("[\\D]", ""));
I can't find the answer online, and the fact that it shouldn't be complicated drives me crazy, I would be grateful if someone could help me!
Do the reverse. If they are increasing starting from the first digit, it means that they are decreasing from the last to the first. And it is much easier to program this way:
public boolean increasingDigits(int input)
{
// Deal with negative inputs...
if (input < 0)
input = -input;
int lastSeen = 10; // always greater than any digit
int current;
while (input > 0) {
current = input % 10;
if (lastSeen < current)
return false;
lastSeen = current;
input /= 10;
}
return true;
}
You can't index an integer (i.e. numblist) using the [] syntax -- that only works for arrays, hence your error. I think you're making this more complicated than it has to be; why not just start from the back of the integer and check if the digits are decreasing, which would avoid all this business with strings:
int n = numblist;
boolean increasing = true;
while (n > 0) {
int d1 = n % 10;
n /= 10;
int d2 = n % 10;
if (d2 > d1) {
increasing = false;
break;
}
}
One way I could think of was this:
boolean checkNumber(int n) {
String check = String.valueOf(n); // Converts n to string.
int length = check.length(); // Gets length of string.
for (int i = 0; i < length-1; i++) {
if(check.charAt(i) <= check.charAt(i+1)) { // Uses the charAt method for comparison.
continue; // if index i <= index i+1, forces the next iteration of the loop.
}
else return false; // if the index i > index i+1, it's not an increasing number. Hence, will return false.
}
return true; // If all digits are in an increasing fashion, it'll return true.
}
I'm assuming that you're checking the individual digits within the integer. If so, it would be best to convert the Integer to a string and then loop though the characters in the string.
public class Test {
public static void main(String[] args) {
Integer num = 234; // New Integer
String string = num.toString(); // Converts the Integer to a string
// Loops through the characters in the string
for(int x = 0; x < string.length() - 1; x++){
// Makes sure that both string.charAt(x) and string.charAt(x+1) are integers
if(string.charAt(x) <= '9' && string.charAt(x) >= '0' && string.charAt(x+1) <= '9' && string.charAt(x+1) >= '0'){
if(Integer.valueOf(string.charAt(x)) < Integer.valueOf(string.charAt(x+1))){
System.out.println("OK");
}else{
System.out.println("NOK");
}
}
}
}
}
I think a simple way could be this
package javacore;
import java.util.Scanner;
// checkNumber
public class Main_exercise4 {
public static void main (String[] args) {
// Local Declarations
int number;
boolean increasingNumber=false;
Scanner input = new Scanner(System.in);
number = input.nextInt();
increasingNumber = checkNumber(number);
System.out.println(increasingNumber);
}
public static boolean checkNumber(int number) {
boolean increasing = false;
while(number>0) {
int lastDigit = number % 10;
number /= 10;
int nextLastDigit = number % 10;
if(nextLastDigit<=lastDigit) {
increasing=true;
}
else {
increasing=false;
break;
}
}
return increasing;
}
}
private boolean isIncreasingOrder(int num) {
String value = Integer.toString(num);
return IntStream.range(0, value.length() - 1).noneMatch(i -> Integer.parseInt(value.substring(i, i + 1)) > Integer.parseInt(value.substring(i + 1, i + 2)));
}
Related
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;
}
how can I use Java to find out numbers that can't be divided by any other number?
i have an int array:
int[] numbers = new int[25];
Now I want to iterate over this array and output all the numbers that are not divisible in a new array. The remaining numbers should no longer appear in the new array.
For example, in a range from 1-25, only the numbers [1,3,5,7,11,13,17,19,23] should be output as an array.
How exactly do I get to program this?
Thanks in advance!
Like #Selvin said in the comments, these numbers have a name, they are called "prime numbers".
For example, you can use something like this:
for (int number : numbers) {
if (!primeCal(number)) {
number = null;
}
}
private static void primeCal(int num) {
int count = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
You must first iterate and then use the following method to check if any of them are prime numbers or not
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
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;
}
In our directions, we have to get a 16 digit number, then sum all the digits in the odd place from right to left. After that, we have to sum all the even place digits from right to left, double the sum, then take module 9. When I try to run my code, I keep getting "Invalid", even if it is with a valid credit card number.
public static boolean validateCreditCard(long number) {
double cardSum = 0;
for (int i = 0; i < 16; i++) {
long cardnumber = (long) Math.pow(10, i);
double oddPlaceSum = 0;
double evenPlaceSum = 0;
if (i % 2 != 0) {
oddPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i))));
} else { // so if i%2 ==0
evenPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i)) * 2 % 9));
}
cardSum += evenPlaceSum + oddPlaceSum;
}
if (cardSum % 10 == 0) {
return true;
System.out.println("Valid");
} else {
return false;
System.out.println("Invalid");
}
}
Try this instead :
Convert the 16 digit number into a String using Long.toString(number).
Iterate through the String character by character and keep track of even and odd indexes.
Convert each char to an Integer using Integer.valueOf() thereby adding them incrementally.
Voila, you got your evenSum and oddSum. Next steps should be trivial.
public static boolean validateCreditCard(long number){
String x = Long.toString(number);
int evenSum = 0;
int oddSum = 0;
for(int i=0; i<x.length; i=i+2) {
oddSum += Integer.valueOf(s[i]);
evenSum += Integer.valueOf(s[i+1]);
}
//Do the next steps with odd and even sums.
Also, do handle IndexOutOfBoundsException as appropriate.
You can do it in a single while loop as digits are fixed, like this:
int digit,evensum,oddsum;
int i=16;
while(i > 0){
digit=number%10;
if(i%2 == 0)
evensum+=digit;
else
oddsum+=digit;
i--;
digit/=10;
}
Try this instead
using Recusion find sum of even placed of digit and sum of odd placed of digit.
class Recursion {
static int count = 0;
static int even =0;
static int odd =0;
public static int Digits(int num) {
if (num > 0) {
count++;
if(count%2 == 0){
even += num%10;
}
else{
odd += num%10;
}
Digits(num / 10);
}
return even;
// for odd
// return odd;
}
public static void main(String[] args) {
int num = 31593;
int res = Digits(num);
System.out.println("Total digits are: " + res);
}
}
Help me How to print both even and odd sum together?
import java.util.Scanner;
import java.io.*;
class factorial {
void fact(int a) {
int i;
int ar[] = new int[10000];
int fact = 1, count = 0;
for (i = 1; i <= a; i++) {
fact = fact * i;
}
String str1 = Integer.toString(fact);
int len = str1.length();
i = 0;
do {
ar[i] = fact % 10;
fact /= 10;
i++;
} while (fact != 0);
for (i = 0; i < len; i++) {
if (ar[i] == 0) {
count = count + 1;
}
}
System.out.println(count);
}
public static void main(String...ab) {
int a;
Scanner input = new Scanner(System.in);
a = input.nextInt();
factorial ob = new factorial();
ob.fact(a);
}
}
This code is work up to a = 10 but after enter number larger then a = 16 it gives wrong answer.
Please help.
As I am not able to post this question if I dont add more info for this question but I assume that the info I provide above is enough to under stand what I want.
Like many of these mathematical puzzles, you are expected to simplify the problem to make it practical. You need to find how many powers of ten in a factorial, not calculate a factorial and then find the number of trailing zeros.
The simplest solution is to count the number of powers of five. The reason you only need to count powers of five is that there is plenty of even numbers in between then to make a 10. For example, 5! has one 0, 10! has 2, 15! has three, 20! has four, and 25! has not five but six as 25 = 5 * 5.
In short you only need calculate the number of powers of five between 1 and N.
// floor(N/5) + floor(N/25) + floor(N/125) + floor(N/625) ...
public static long powersOfTenForFactorial(long n) {
long sum = 0;
while (n >= 5) {
n /= 5;
sum += n;
}
return sum;
}
Note: This will calculate the trailing zeros of Long.MAX_VALUE! in a faction of a second, whereas trying this with BigInteger wouldn't fit, no matter how much memory you had.
Please Note, this is not the mathematical solution as others suggested, this is just a refactoring of what he had initially...
Here I just used BigInteger in place of Int, and simplified your code abit. Your solution is still not optimal. I thought I would just show you what a refactored version of what you posted may look like. Also there was a bug in your initial function. It returned the number of zeros in the whole number instead of just the number of trailing zeros.
import java.math.BigInteger;
import java.util.Scanner;
class factorial {
public static void main(String... ab) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
fact(a);
}
private static void fact(int a) {
BigInteger fact = BigInteger.ONE;
int i, count = 0;
for (i = 1; i <= a; i++) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
String str1 = fact.toString();
for(int j = str1.length() - 1; j > -1; j--) {
if(Character.digit(str1.charAt(j), 10) != 0) {
System.out.println(count);
break;
} else {
count++;
}
}
}
}
Without using factorial
public class TrailingZero {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(trailingZeroes(9247));
}
public static int trailingZeroes(int a) {
int countTwo = 0;
int countFive = 0;
for (int i = a; i > 1; i--) {
int local = i;
while (local > 1) {
if (local % 2 != 0) {
break;
}
local = local / 2;
countTwo++;
}
while (local > 1) {
if (local % 5 != 0) {
break;
} else {
local = local / 5;
countFive++;
}
}
}
return Math.min(countTwo, countFive);
}}