Check if number of digits of an integer is even with recursion - java

Need to check if number of digits of an integer is even with recursion.
Here is without recursion:
private static boolean jeParanBrCifara(int n) {
int brojCifara = String.valueOf(n).length();
if (brojCifara % 2 == 0)
return true;
else
return false;
}
and here is code for counting numbers with the recursion
public int DigitsCount(int Number) {
if (Number > 0) {
Count = Count + 1;
DigitsCount(Number / 10);
}
return Count;
}
But how to make an recursive method that will take an integer as parameter and return true (if number of digits is even) of false ?
I did this, but not sure if it is correct:
static int Count = 0;
public static boolean isEven(int Number) {
boolean even = false;
if (Number > 0) {
Count = Count + 1;
isEven(Number / 10);
}
if (Count % 2 == 0) {
even = true;
}
return even;
}
Any tips/hints?

Consider how the answer changes as you increase the number of digits:
1 digit - false
2 digits - true
3 digit - false
4 digits - true
and so on
See the pattern? The answer to a problem with one digit is false, and the answer to a problem with n+1 digits is the inverse of the answer for the problem with n digits.
Since you already know that reducing the number of digits by one is done by dividing by 10 in integers, you should be able to write a solution to the above algorithm with just a few lines of code.

Recursion is to express the function in terms of itself, but for a smaller problem. Something like this:
If the number is 9 or lower, it's false.
If the number is 99 or lower, it's true.
Otherwise, divide by 100 and check if the result has an even number of digits...

Since we know that Number%2 will return 0 or 1, i'm going to assume that you shouldn't be using that to determinate if the number is even or odd.
You should set your base case (If 1 then return false)
Then check if the n-1 was even or odd and return the opposite.

Let's assume we're only dealing with positive numbers, something like this could be written:
public static boolean IsEven(int n)
{
return n >= 10
? !IsEven(n / 10)
: false;
}

On the same line as mentioned by dasblinkenlight above
public static boolean isEven(int num){
if(num>=10){
return !isEven(num/10);
}
return false;
}

Related

sum of first and last digit in the integer

The method written in the below code needs to take integer and result sum of 1st digit and last digit in the integer.
NOTE: The reason i am asking this question though i got to know the correct solution is i need to understand why my code is not working also as that makes me a better programmer please help.
public class FirstLastDigitSum {
public static int sumFirstAndLastDigit(int number)//to add first and last
//digits of a given interger
{
int firstdigit=0;
int lastdigit=0;
if(number>=0 && number<=9)
{
return number+number;
}
else if(number>9)
{
lastdigit=number%10;
while(number>0)
{
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
}
return firstdigit+lastdigit;
}
else
return -1;
}
public static void main(String[] args)
{
System.out.println(sumFirstAndLastDigit(121));
}
}
In the above code if i keep number/=10 after if block like below
if(number<=9 & number>=0){
firstdigit=number;
}
number/=10;
then my code is giving proper results. like if i input 121 to the method as first digit is 1 and second digit is 1 it is summing both and giving me result 2. which is absolutely correct
But if keep number/=10 above the if block like below
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
Then my code is not giving proper result it is giving only last number which is 1.
I am not at all understanding why this is happening can any one explain please.
Lets break this up into two parts. Get the last digit of the number, and getting the first digit of the number.
The first part of the problem is easy. Its exactly what you already have; just take modulo 10 of the number.
int lastdigit = number % 10;
The second part is a little trickier, but not too much. While the number is greater than 10 divide it by 10 (using integers you will have truncation for the remainder). One problem I see in your solution is that you keep checking the value even after a digit is discovered. That means if the value was 1234, you correctly find 1, but then overwrite it to 0 with an extra loop iteration
int firstdigit = number;
while (firstdigit >= 10) {
firstdigit /= 10;
}
And that's it, you are done. Just return the value.
return firstdigit + lastdigit;
If the number is less than 0 then return -1. Otherwise the last number can be found by modulus 10, and the first number found by dividing by 10 until that number is less than 10.
public static int sumFirstAndLastDigit(int number) {
if (number < 0) {
return -1;
}
int last = number % 10;
int first = number;
while (first >= 10) {
first = first / 10;
}
return first + last;
}
In this case:
while(number>0)
{
number/=10;
if(number<=9 & number>=0){
firstdigit=number;
}
}
Note that you change number after you check number > 0. That means that number can be 0 when reaches the if statement and if it is 0 it will be accepted as first digit because it satisfies the condition number<=9 & number>=0. As an example, when you test it with 121 you have this values for number 121, 12, 1 and 0. The last one satisfies the if statement and set first digit to 0.
In this case:
while(number>0)
{
if(number<=9 & number>=0){
firstdigit=number;
}
number/=10;
}
You change number before you check number > 0. That means that the if statement will never have a number = 0 and firstdigit will never be 0. As an example, when you test it with 121 you have this values for number 121, 12, and 1. The last one satisfies the if statement and set first digit to 1. After that you divide number by zero and it becomes 0 and it stop the while loop.
This is not a direct solution to your problem, but we can fairly easily handle this using regex and the base methods:
int number = 12345678;
String val = String.valueOf(number);
val = val.replaceAll("(?<=\\d)\\d+(?=\\d)", "");
number = Integer.parseInt(val);
int sum = number % 10 + number / 10;
System.out.println(sum);

Java: Incorrect Output when Factoring

I'm trying to write a function to determine whether a number is "ugly". For a number to be "ugly", it must have no prime factors other than 2, 3, or 5.
Here's my attempt:
public class Solution {
public boolean isPrime(int num) {
if (num == 2) {
return true;
}
if (num % 2 == 0) {
return false;
}
if (num < 0) {
num *= -1;
}
for (int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
public boolean isUgly(int num) {
if (num < 0) {
num *= -1;
}
for (int i = 7; i <= Math.sqrt(num); i += 2) {
if ((num % i == 0) && isPrime(num)) {
return false;
}
}
return true;
}
}
I'm getting true for input = -2147483648 when it should be false. Is it possible there's an overflow here? I've gone over my code and the logic looks right to me...
Thanks!
The problem is Integer.MIN_VALUE*-1 = Integer.MIN_VALUE leading to Math.sqrt(Integer.MIN_VALUE) which returns NaN on a negative number, so then when you perform this operation 7 <= Math.sqrt(Integer.MIN_VALUE) it returns false and doesn't even enter the for loop resulting in the program returning true.
I hope this explanation helps.
Yeah, I guess so.
Java lower limit for int is -2147483648 and upper 2147483647. As shown in
public class MainClass {
public static void main(String[] arg) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
}
Negative numbers are tricky in such a question.
You have to take the absolute number and factor it. In your original source, you didn't do this. It meant that you got a NaN from the Math.sqrt method. Which also meant that you got false when you compared it to 7.
So your original method would have returned true for all negative numbers.
But changing the sign (which, by the way can be done by num = -num rather than multiplication), which would solve it for all negative numbers, actually introduced an overflow into the program.
The number -2147483648 is, in fact, -231. The maximum positive number allowed in an int is 231-1. So the number - Integer.MIN_VALUE always overflows... into itself. It remains negative after you negate it!
So you run into that NaN again.
But note - since the number is -231, it doesn't, in fact, have any other prime factors other than 2. So the method really should return true for it - assuming that you are not considering -1 a prime.
So I believe that your expectation that it should be false is incorrect - but it depends on the assignment's definition of the prime factors of negative numbers.
Notes:
Your program checks isPrime(num) instead of isPrime(i), and therefore it will always return true. num cannot both be divisible by i and be prime at the same time.
Limiting your program to the square root of num is wrong to begin with. For example, take the number 881305274. Its prime factors are 2 and 440652637. But 440652637 is much bigger than sqrt(881305274). The square root trick works for prime testing, because any factor that is bigger than the root has to be multiplied by a factor that's smaller than the root. But this doesn't apply to the "ugly" problem.
Also, prime numbers are not considered "ugly" as they are a factor of themselves. But your program, because it limits itself to the square root, will never return false for prime numbers.

Recursion task in Java

public static boolean sameNumbers(int number) {
boolean isSame;
isSame = (number % 10) == (number / 10) % 10;
sameNumbers(number / 10);
return isSame;
}
My task is to implement a method which checks if the given int value has all the same numbers (e.g. 666 or 1111). However, the requirement is that I should just choose recursion and no iteration.
I am aware that my method wouldn't work, but I really don't know how I can solve this problem without any if statements. Any ideas?
You have the right approach. It's just a matter of combining the base case with the recursive component. If you want to avoid if, just do this:
public static boolean sameNumbers(int number) {
return number < 10 || ((number % 10) == (number / 10) % 10)
&& sameNumbers(number / 10));
}
When tackling a recursion problem, you have to split it into a base case and a recurse case. So for instance, you know that any number with one digit contains all the same digit. That would be your base case.
For numbers with more than one digit, you could check two digits, and fail fast if they don't match. If they do match, then chop one off and return the test against the shortened number.
For a more spelled out implementation:
public static bool sameNumbers(int number) {
int onesPlace = number % 10;
int shifted = number / 10;
int tensPlace = shifted % 10;
return onesPlace == number || (onesPlace == tensPlace && sameNumbers(shifted));
}
Depending on your definition of correct, this will handle negative numbers correctly.
If you are allowed to use if statements, this will save you a few instructions:
public static bool sameNumbers(int number) {
int onesPlace = number % 10;
if (onesPlace == number) {
return true;
}
int shifted = number / 10;
int tensPlace = shifted % 10;
return onesPlace == tensPlace && sameNumbers(shifted);
}

Check whether number is even or odd

How would I determine whether a given number is even or odd? I've been wanting to figure this out for a long time now and haven't gotten anywhere.
You can use the modulus operator, but that can be slow. If it's an integer, you can do:
if ( (x & 1) == 0 ) { even... } else { odd... }
This is because the low bit will always be set on an odd number.
if ((x % 2) == 0) {
// even
} else {
// odd
}
If the remainder when you divide by 2 is 0, it's even. % is the operator to get a remainder.
The remainder operator, %, will give you the remainder after dividing by a number.
So n % 2 == 0 will be true if n is even and false if n is odd.
Every even number is divisible by two, regardless of if it's a decimal (but the decimal, if present, must also be even). So you can use the % (modulo) operator, which divides the number on the left by the number on the right and returns the remainder...
boolean isEven(double num) { return ((num % 2) == 0); }
I would recommend
Java Puzzlers: Traps, Pitfalls, and Corner Cases Book by Joshua Bloch
and Neal Gafter
There is a briefly explanation how to check if number is odd.
First try is something similar what #AseemYadav tried:
public static boolean isOdd(int i) {
return i % 2 == 1;
}
but as was mentioned in book:
when the remainder operation returns a nonzero result, it has the same
sign as its left operand
so generally when we have negative odd number then instead of 1 we'll get -1 as result of i%2. So we can use #Camilo solution or just do:
public static boolean isOdd(int i) {
return i % 2 != 0;
}
but generally the fastest solution is using AND operator like #lucasmo write above:
public static boolean isOdd(int i) {
return (i & 1) != 0;
}
#Edit
It also worth to point Math.floorMod(int x, int y); which deals good with negative the dividend but also can return -1 if the divisor is negative
Least significant bit (rightmost) can be used to check if the number is even or odd.
For all Odd numbers, rightmost bit is always 1 in binary representation.
public static boolean checkOdd(long number){
return ((number & 0x1) == 1);
}
Works for positive or negative numbers
int start = -3;
int end = 6;
for (int val = start; val < end; val++)
{
// Condition to Check Even, Not condition (!) will give Odd number
if (val % 2 == 0)
{
System.out.println("Even" + val);
}
else
{
System.out.println("Odd" + val);
}
}
If the modulus of the given number is equal to zero, the number is even else odd number. Below is the method that does that:
public void evenOrOddNumber(int number) {
if (number % 2 == 0) {
System.out.println("Number is Even");
} else {
System.out.println("Number is odd");
}
}
This following program can handle large numbers ( number of digits greater than 20 )
package com.isEven.java;
import java.util.Scanner;
public class isEvenValuate{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String digit = in.next();
int y = Character.getNumericValue(digit.charAt(digit.length()-1));
boolean isEven = (y&1)==0;
if(isEven)
System.out.println("Even");
else
System.out.println("Odd");
}
}
Here is the output ::
122873215981652362153862153872138721637272
Even
/**
* Check if a number is even or not using modulus operator.
*
* #param number the number to be checked.
* #return {#code true} if the given number is even, otherwise {#code false}.
*/
public static boolean isEven(int number) {
return number % 2 == 0;
}
/**
* Check if a number is even or not using & operator.
*
* #param number the number to be checked.
* #return {#code true} if the given number is even, otherwise {#code false}.
*/
public static boolean isEvenFaster(int number) {
return (number & 1) == 0;
}
source
You can use the modulus operator, but that can be slow. A more efficient way would be to check the lowest bit because that determines whether a number is even or odd. The code would look something like this:
public static void main(String[] args) {
System.out.println("Enter a number to check if it is even or odd");
System.out.println("Your number is " + (((new Scanner(System.in).nextInt() & 1) == 0) ? "even" : "odd"));
}
You can do like this:
boolean is_odd(int n) {
return n % 2 == 1 || n % 2 == -1;
}
This is because Java has in its modulo operation the sign of the dividend, the left side: n.
So for negatives and positives dividends, the modulo has the sign of them.
Of course, the bitwise operation is faster and optimized, simply document the line of code with two or three short words, which does it for readability.
Another easy way to do it without using if/else condition (works for both positive and negative numbers):
int n = 8;
List<String> messages = Arrays.asList("even", "odd");
System.out.println(messages.get(Math.abs(n%2)));
For an Odd no., the expression will return '1' as remainder, giving
messages.get(1) = 'odd' and hence printing 'odd'
else, 'even' is printed when the expression comes up with result '0'
package isevenodd;
import java.util.Scanner;
public class IsEvenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number: ");
int y = scan.nextInt();
boolean isEven = (y % 2 == 0) ? true : false;
String x = (isEven) ? "even" : "odd";
System.out.println("Your number is " + x);
}
}
Here is full example:-
import java.text.ParseException;
public class TestOddEvenExample {
public static void main(String args[]) throws ParseException {
int x = 24;
oddEvenChecker(x);
int xx = 3;
oddEvenChecker(xx);
}
static void oddEvenChecker(int x) {
if (x % 2 == 0)
System.out.println("You entered an even number." + x);
else
System.out.println("You entered an odd number." + x);
}
}

Prime Factorization Program in Java

I am working on a prime factorization program implemented in Java.
The goal is to find the largest prime factor of 600851475143 (Project Euler problem 3).
I think I have most of it done, but I am getting a few errors.
Also my logic seems to be off, in particular the method that I have set up for checking to see if a number is prime.
public class PrimeFactor {
public static void main(String[] args) {
int count = 0;
for (int i = 0; i < Math.sqrt(600851475143L); i++) {
if (Prime(i) && i % Math.sqrt(600851475143L) == 0) {
count = i;
System.out.println(count);
}
}
}
public static boolean Prime(int n) {
boolean isPrime = false;
// A number is prime iff it is divisible by 1 and itself only
if (n % n == 0 && n % 1 == 0) {
isPrime = true;
}
return isPrime;
}
}
Edit
public class PrimeFactor {
public static void main(String[] args) {
for (int i = 2; i <= 600851475143L; i++) {
if (isPrime(i) == true) {
System.out.println(i);
}
}
}
public static boolean isPrime(int number) {
if (number == 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i = 3; i <= number; i++) {
if (number % i == 0) return false;
}
return true;
}
}
Why make it so complicated? You don't need do anything like isPrime(). Divide it's least divisor(prime) and do the loop from this prime. Here is my simple code :
public class PrimeFactor {
public static int largestPrimeFactor(long number) {
int i;
for (i = 2; i <= number; i++) {
if (number % i == 0) {
number /= i;
i--;
}
}
return i;
}
/**
* #param args
*/
public static void main(String[] args) {
System.out.println(largestPrimeFactor(13195));
System.out.println(largestPrimeFactor(600851475143L));
}
}
edit: I hope this doesn't sound incredibly condescending as an answer. I just really wanted to illustrate that from the computer's point of view, you have to check all possible numbers that could be factors of X to make sure it's prime. Computers don't know that it's composite just by looking at it, so you have to iterate
Example: Is X a prime number?
For the case where X = 67:
How do you check this?
I divide it by 2... it has a remainder of 1 (this also tells us that 67 is an odd number)
I divide it by 3... it has a remainder of 1
I divide it by 4... it has a remainder of 3
I divide it by 5... it has a remainder of 2
I divide it by 6... it has a remainder of 1
In fact, you will only get a remainder of 0 if the number is not prime.
Do you have to check every single number less than X to make sure it's prime? Nope. Not anymore, thanks to math (!)
Let's look at a smaller number, like 16.
16 is not prime.
why? because
2*8 = 16
4*4 = 16
So 16 is divisible evenly by more than just 1 and itself. (Although "1" is technically not a prime number, but that's technicalities, and I digress)
So we divide 16 by 1... of course this works, this works for every number
Divide 16 by 2... we get a remainder of 0 (8*2)
Divide 16 by 3... we get a remainder of 1
Divide 16 by 4... we get a remainder of 0 (4*4)
Divide 16 by 5... we get a remainder of 1
Divide 16 by 6... we get a remainder of 4
Divide 16 by 7... we get a remainder of 2
Divide 16 by 8... we get a remainder of 0 (8*2)
We really only need one remainder of 0 to tell us it's composite (the opposite of "prime" is "composite").
Checking if 16 is divisible by 2 is the same thing as checking if it's divisible by 8, because 2 and 8 multiply to give you 16.
We only need to check a portion of the spectrum (from 2 up to the square-root of X) because the largest number that we can multiply is sqrt(X), otherwise we are using the smaller numbers to get redundant answers.
Is 17 prime?
17 % 2 = 1
17 % 3 = 2
17 % 4 = 1 <--| approximately the square root of 17 [4.123...]
17 % 5 = 2 <--|
17 % 6 = 5
17 % 7 = 3
The results after sqrt(X), like 17 % 7 and so on, are redundant because they must necessarily multiply with something smaller than the sqrt(X) to yield X.
That is,
A * B = X
if A and B are both greater than sqrt(X) then
A*B will yield a number that is greater than X.
Thus, one of either A or B must be smaller than sqrt(X), and it is redundant to check both of these values since you only need to know if one of them divides X evenly (the even division gives you the other value as an answer)
I hope that helps.
edit: There are more sophisticated methods of checking primality and Java has a built-in "this number is probably prime" or "this number is definitely composite" method in the BigInteger class as I recently learned via another SO answer :]
You need to do some research on algorithms for factorizing large numbers; this wikipedia page looks like a good place to start. In the first paragraph, it states:
When the numbers are very large, no efficient integer factorization algorithm is publicly known ...
but it does list a number of special and general purpose algorithms. You need to pick one that will work well enough to deal with 12 decimal digit numbers. These numbers are too large for the most naive approach to work, but small enough that (for example) an approach based on enumerating the prime numbers starting from 2 would work. (Hint - start with the Sieve of Erasthones)
Here is very elegant answer - which uses brute force (not some fancy algorithm) but in a smart way - by lowering the limit as we find primes and devide composite by those primes...
It also prints only the primes - and just the primes, and if one prime is more then once in the product - it will print it as many times as that prime is in the product.
public class Factorization {
public static void main(String[] args) {
long composite = 600851475143L;
int limit = (int)Math.sqrt(composite)+1;
for (int i=3; i<limit; i+=2)
{
if (composite%i==0)
{
System.out.println(i);
composite = composite/i;
limit = (int)Math.sqrt(composite)+1;
i-=2; //this is so it could check same prime again
}
}
System.out.println(composite);
}
}
You want to iterate from 2 -> n-1 and make sure that n % i != 0. That's the most naive way to check for primality. As explained above, this is very very slow if the number is large.
To find factors, you want something like:
long limit = sqrt(number);
for (long i=3; i<limit; i+=2)
if (number % i == 0)
print "factor = " , i;
In this case, the factors are all small enough (<7000) that finding them should take well under a second, even with naive code like this. Also note that this particular number has other, smaller, prime factors. For a brute force search like this, you can save a little work by dividing out the smaller factors as you find them, and then do a prime factorization of the smaller number that results. This has the advantage of only giving prime factors. Otherwise, you'll also get composite factors (e.g., this number has four prime factors, so the first method will print out not only the prime factors, but the products of various combinations of those prime factors).
If you want to optimize that a bit, you can use the sieve of Eratosthenes to find the prime numbers up to the square root, and then only attempt division by primes. In this case, the square root is ~775'000, and you only need one bit per number to signify whether it's prime. You also (normally) only want to store odd numbers (since you know immediately that all even numbers but two are composite), so you need ~775'000/2 bits = ~47 Kilobytes.
In this case, that has little real payoff though -- even a completely naive algorithm will appear to produce results instantly.
I think you're confused because there is no iff [if-and-only-if] operator.
Going to the square root of the integer in question is a good shortcut. All that remains is checking if the number within that loop divides evenly. That's simply [big number] % i == 0. There is no reason for your Prime function.
Since you are looking for the largest divisor, another trick would be to start from the highest integer less than the square root and go i--.
Like others have said, ultimately, this is brutally slow.
private static boolean isPrime(int k) throws IllegalArgumentException
{
int j;
if (k < 2) throw new IllegalArgumentException("All prime numbers are greater than 1.");
else {
for (j = 2; j < k; j++) {
if (k % j == 0) return false;
}
}
return true;
}
public static void primeFactorsOf(int n) {
boolean found = false;
if (isPrime(n) == true) System.out.print(n + " ");
else {
int i = 2;
while (found == false) {
if ((n % i == 0) && (isPrime(i))) {
System.out.print(i + ", ");
found = true;
} else i++;
}
primeFactorsOf(n / i);
}
}
For those answers which use a method isPrime(int) : boolean, there is a faster algorithm than the one previously implemented (which is something like)
private static boolean isPrime(long n) { //when n >= 2
for (int k = 2; k < n; k++)
if (n % k == 0) return false;
return true;
}
and it is this:
private static boolean isPrime(long n) { //when n >= 2
if (n == 2 || n == 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int k = 1; k <= (Math.floor(Math.sqrt(n)) + 1) / 6; k++)
if (n % (6 * k + 1) == 0 || n % (6 * k - 1) == 0) return false;
return true;
}
I made this algorithm using two facts:
We only need to check for n % k == 0 up to k <= Math.sqrt(n). This is true because for anything higher, factors merely "flip" ex. consider the case n = 15, where 3 * 5 = 5 * 3, and 5 > Math.sqrt(15). There is no need for this overlap of checking both 15 % 3 == 0 and 15 % 5 == 0, when we could just check one of these expressions.
All primes (excluding 2 and 3) can be expressed in the form (6 * k) + 1 or (6 * k) - 1, because any positive integer can be expressed in the form (6 * k) + n, where n = -1, 0, 1, 2, 3, or 4 and k is an integer <= 0, and the cases where n = 0, 2, 3, and 4 are all reducible.
Therefore, n is prime if it is not divisible by 2, 3, or some integer of the form 6k ± 1 <= Math.sqrt(n). Hence the above algorithm.
--
Wikipedia article on testing for primality
--
Edit: Thought I might as well post my full solution (*I did not use isPrime(), and my solution is nearly identical to the top answer, but I thought I should answer the actual question):
public class Euler3 {
public static void main(String[] args) {
long[] nums = {13195, 600851475143L};
for (num : nums)
System.out.println("Largest prime factor of " + num + ": " + lpf(num));
}
private static lpf(long n) {
long largestPrimeFactor = 1;
long maxPossibleFactor = n / 2;
for (long i = 2; i <= maxPossibleFactor; i++)
if (n % i == 0) {
n /= i;
largestPrimeFactor = i;
i--;
}
return largestPrimeFactor;
}
}
To find all prime factorization
import java.math.BigInteger;
import java.util.Scanner;
public class BigIntegerTest {
public static void main(String[] args) {
BigInteger myBigInteger = new BigInteger("65328734260653234260");//653234254
BigInteger originalBigInteger;
BigInteger oneAddedOriginalBigInteger;
originalBigInteger=myBigInteger;
oneAddedOriginalBigInteger=originalBigInteger.add(BigInteger.ONE);
BigInteger index;
BigInteger countBig;
for (index=new BigInteger("2"); index.compareTo(myBigInteger.add(BigInteger.ONE)) <0; index = index.add(BigInteger.ONE)){
countBig=BigInteger.ZERO;
while(myBigInteger.remainder(index) == BigInteger.ZERO ){
myBigInteger=myBigInteger.divide(index);
countBig=countBig.add(BigInteger.ONE);
}
if(countBig.equals(BigInteger.ZERO)) continue;
System.out.println(index+ "**" + countBig);
}
System.out.println("Program is ended!");
}
}
I got a very similar problem for my programming class. In my class it had to calculate for an inputted number. I used a solution very similar to Stijak. I edited my code to do the number from this problem instead of using an input.
Some differences from Stijak's code are these:
I considered even numbers in my code.
My code only prints the largest prime factor, not all factors.
I don't recalculate the factorLimit until I have divided all instances of the current factor off.
I had all the variables declared as long because I wanted the flexibility of using it for very large values of number. I found the worst case scenario was a very large prime number like 9223372036854775783, or a very large number with a prime number square root like 9223371994482243049. The more factors a number has the faster the algorithm runs. Therefore, the best case scenario would be numbers like 4611686018427387904 (2^62) or 6917529027641081856 (3*2^61) because both have 62 factors.
public class LargestPrimeFactor
{
public static void main (String[] args){
long number=600851475143L, factoredNumber=number, factor, factorLimit, maxPrimeFactor;
while(factoredNumber%2==0)
factoredNumber/=2;
factorLimit=(long)Math.sqrt(factoredNumber);
for(factor=3;factor<=factorLimit;factor+=2){
if(factoredNumber%factor==0){
do factoredNumber/=factor;
while(factoredNumber%factor==0);
factorLimit=(long)Math.sqrt(factoredNumber);
}
}
if(factoredNumber==1)
if(factor==3)
maxPrimeFactor=2;
else
maxPrimeFactor=factor-2;
else
maxPrimeFactor=factoredNumber;
if(maxPrimeFactor==number)
System.out.println("Number is prime.");
else
System.out.println("The largest prime factor is "+maxPrimeFactor);
}
}
public class Prime
{
int i;
public Prime( )
{
i = 2;
}
public boolean isPrime( int test )
{
int k;
if( test < 2 )
return false;
else if( test == 2 )
return true;
else if( ( test > 2 ) && ( test % 2 == 0 ) )
return false;
else
{
for( k = 3; k < ( test/2 ); k += 2 )
{
if( test % k == 0 )
return false;
}
}
return true;
}
public void primeFactors( int factorize )
{
if( isPrime( factorize ) )
{
System.out.println( factorize );
i = 2;
}
else
{
if( isPrime( i ) && ( factorize % i == 0 ) )
{
System.out.print( i+", " );
primeFactors( factorize / i );
}
else
{
i++;
primeFactors( factorize );
}
}
public static void main( String[ ] args )
{
Prime p = new Prime( );
p.primeFactors( 649 );
p.primeFactors( 144 );
p.primeFactors( 1001 );
}
}

Categories

Resources