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;
}
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;
}
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?
I have a small problem understanding what my teacher wants me to do. What I have made is a code that saves me all the Prime numbers in an Array that can be displayed. But now he wants me to "optimize" the code with, as far as I understand, try to divide a number only by the numbers that are prime. For example : if I have 2,3,5 the next number to be prime is the number that doesn't divide by any of this. So I don't have to try 2,3,4,5 but only 2,3,5 (the numbers that I have in the array). And for example : 2,3,4,5,7 are primes, 10 is not because it divides by 2 then it has to jump on the next number.
public static void main(String[] args) {
String introducedNumber = JOptionPane.showInputDialog("Introduce a number"); //with JOptionPane imported will ask you a small box for a number
int number, divider, numberDividing; //declaring the int's
number = Integer.parseInt(introducedNumber); //converting the input to a int
int x = 0; //starting X to 0 since its 1st array position
int[] arrayPrime = new int[number]; //declaring and creating an array
for (divider = 1; divider <= number; divider++) { //for to run till numbers
//for that checks if the number divides by any other than himself
for (numberDividing = 2; (numberDividing < divider) && (divider % numberDividing != 0); numberDividing++) {
}
if (numberDividing >= divider) {
arrayPrime[x] = divider;
x++;
}
}
for (int i = 0; i < x; i++) {
System.out.println(arrayPrime[i]);
}
}
}
At the moment your code to check whether a number is prime is:
for (numberDividing = 2; (numberDividing < divider) && (divider % numberDividing != 0); numberDividing++) {
}
if (numberDividing >= divider) {
arrayPrime[x] = divider;
x++;
}
So it is checking all numbers from 2 to the last prime. But there's no need for it to do that: it only needs to check the primes you already have in your array.
To make your code a bit more readable, I suggest moving your check to a separate private method. I've also renamed x to primeCount:
private boolean isPrime(int number) {
for (int i = 0; i < primeCount; i++) {
if (number % arrayPrime[i] == 0)
return false;
}
return true;
}
Then your calling code becomes:
for (int divider = 2; divider <= number; divider++) {
if (isPrime(divider))
arrayPrime[primeCount++] = divider;
}
There is another fairly trivial optimisation you can do. You don't need to check any primes that are greater than the square root of the test number because you've already checked smaller factors at that point:
private boolean isPrime(int number) {
for (int i = 0; i < primeCount; i++) {
int prime = arrayPrime[i];
if (prime * prime > number)
break;
else if (number % prime == 0)
return false;
}
return true;
}
If you don't want to use a separate method, then:
for (int divider = 2; divider <= number; divider++) {
boolean isPrime = true;
for (int i = 0; i < primeCount && isPrime; i++) {
isPrime = number % arrayPrime[i] > 0;
}
if (isPrime)
arrayPrime[primeCount++] = divider;
}
And, for your future study, here's a more elegant way to achieve the same result using a prime number generator:
public class PrimeGenerator {
private long current = 1;
private final List<Long> primes = new ArrayList<>();
public long next() {
do {
current++;
} while (primes.stream().anyMatch(n -> current % n == 0));
primes.add(current);
return current;
}
}
You were right that you only need to divide new numbers by previously discover primes. What I do below is simply loop through all the discovered primes and use a boolean to keep track of if each number is prime. I also use an ArrayList instead of an array so that there are not numerous unused blocks like in your original array. Hope this helps!
ArrayList<Integer> arrayPrime = new ArrayList<Integer>(); //use array list instead of static array
arrayPrime.add(2); //seed first prime number
boolean isPrime; //boolean to determine if prime
for (divider = 3; divider <= number; divider++) { //loop up to input number, starting at 3
isPrime = true; //initialize true for each new number
for (i = 0; i < arrayPrime.size(); i++) { //loop through each previous prime
if (divider % arrayPrime[i] == 0) { //see if number is divisible by previous prime
isPrime = false;
break; //break out of loop
}
}
if(isPrime){ //if it did not divide evenly, it is prime
ArrayPrime.add(divider);
}
}
System.out.println(list);
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)));
}
So i have this problem where when i factor a number, lets say 15, i have to display this: 15=3x5 but instead what i get is 3x5x5 and i have no clue of how to make it that so it only displays 3x5. And then another problem i have is to find whether the number i inputted is a prime number or not. Any way of fixing this? I just need that and the other stuff im gonna edit after that.
public class PrimeFactor
{
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
int a;
int d;
int remainder=0;
int count=2;
int c=0;
String s;
System.out.println("Enter an integer to be factored:");
a=input.nextInt();
s="";
d=a;
while(a>1)
{
if(a>1)
{
s="";
while(a>1)
{
remainder=a%count;
if (!(remainder>0))
while(remainder==0)
{
remainder=a%count;
if (remainder==0)
{
a=a/count;
c=c+1;
s=s+count+"x";
if (a==1)
s=s+count;
}
else
count++;
}
else
count++;
}
if (a%count==0)
{
System.out.println(d +"=" + s);
System.out.println(d+" is a prime number.");
}
else
System.out.println(d +"=" + s);
}
// TODO code application logic here
}
}
}
This determines if the number is prime or not the quickest way. Another method would be to use a for loop to determine the number of factors for the number and then say it's prime if it has more than two factors.
int num; // is the number being tested for if it's prime.
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) // only have to test until the square root of the number
{
if (num%i == 0) // if the number is divisible by anything from 2 - the square root of the number
{
isPrime = false; // it is not prime
break; // break out of the loop because it's not prime and no more testing needed
}
}
if (isPrime)
{
System.out.println(num + " is a prime number.");
}
else
{
System.out.println(num + " is a composite number.");
}
You are not constructing the factorization string quite right:
When you find that 3 divides a=15 you set s to 3x and set a to the quotient, so a=5
When you find that 5 divides a=5 you append 5x to s, so now s is 3x5x. Then you set a to the quotient, which is 1. Since the quotient is now 1, you append 5 again, so now you get 3x5x5.
What you'll want to do is append only 5 when a=1, not 5x5. You have to change this:
s=s+count+"x";
if (a==1)
s=s+count;
to this:
if (a==1) {
s=s+count;
} else {
s=s+count+"x";
}
How about trying like this:-
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("Number is a prime");
else
System.out.println("Number is not a prime");
break;
}
}
These are quite straight-forward methods you can use to factor a number and determine if it is a prime number:
public static int oneFactor(int i) {
for (int j = 2; j < i; j++) {
if (i % j == 0)
return j;
}
return -1;
}
public static Integer[] primeFactors(int i) {
List<Integer> factors = new ArrayList<Integer>();
boolean cont = true;
while (cont) {
int f = oneFactor(i);
if (i > 1 && f != -1) {
i /= f;
factors.add(f);
} else
factors.add(i);
if (f == -1)
cont = false;
}
return factors.toArray(new Integer[factors.size()]);
}
public static boolean isPrime(int i) {
if (i == 2 || i == 3)
return true;
if (i < 2 || i % 2 == 0)
return false;
for (int j = 3, end = (int) Math.sqrt(i); j <= end; j += 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
I am sure one can use faster algorithms, but those would be at the cost of simplicity, and it doesn't seem like you need high speed methods.
They all operate on ints, but its easy to change them to work with longs.
If you have any questions, feel free to ask!
You want to write a loop which loops through numbers 1 to (Inputted Number). And if you found a factor, you print it and divide the input by the factor. (And test if it can be divided again by the same number), else then skip to the next number.
Keep doing this until your input divides down to 1.
This program will break the number down to prime factors:
public class Factor {
public static void main() {
//Declares Variables
int factor = 15;
int i = 2;
System.out.println("Listing Factors:\n");
while (factor>1) {
//Tests if 'i' is a factor of 'factor'
if (factor%i == 0) {
//Prints out and divides factor
System.out.println(i);
factor = factor/i;
} else {
//Skips to next Number
i++;
}
}
}
}
Output:
Listing Factors:
3
5