Java Math Formula Loops - java

how do you add formula n! = 1 * 2 * 3 * i in java that it will be in a loop. An example is if the user inputs 5 the output will be 1 * 2 * 3 * 4 * 5 = 120. If you input 4 the output will be 1 * 2 * 3 * 4 = 24

Do like this:
public int formulaMethod(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
Hope it helps

You can use recursion to solve this problem:
public static int factorial(int n)
{
if (n == 0)
{
return 1;
}
else
{
return (n * factorial(n-1));
}
}

Related

IMEI validation java convert string to long losing leading 0

I am trying to validate IMEI numbers using the code below, the user will enter their number on a page and this then runs isValidIMEI using a string that is converted to a long.
Now this does work for almost all IMEI's that I have come across but for a few iPhone 5's they have a leading 0, so 0133xxxxxxxxxx0 for example. When this is casted to a long the leading 0 is lost so it becomes 14 digits and fails, if I turn off the length checker this still won't work as it will be doubling the wrong digits.
Any idea how I can convert to some kind of number format but keep that leading 0?
/**
* Sum digits
*
* #param n
* #return
*/
private static int sumDig(int n)
{
int a = 0;
while (n > 0)
{
a = a + n % 10;
n = n / 10;
}
return a;
}
/**
* Is valid imei
*
* #param n
* #return
*/
public boolean isValidIMEI(long n)
{
// Converting the number into String
// for finding length
String s = Long.toString(n);
int len = s.length();
Log.v("IMEIValidation", s);
if (len != 15) {
Log.v("IMEIValidation", "Length issue");
return false;
}
int sum = 0;
for (int i = len; i >= 1; i--)
{
int d = (int)(n % 10);
// Doubling every alternate digit
if (i % 2 == 0)
d = 2 * d;
// Finding sum of the digits
sum += sumDig(d);
n = n / 10;
}
Log.v("IMEIValidation", String.valueOf(sum));
Log.v("IMEIValidation", String.valueOf(sum % 10));
return (sum % 10 == 0);
}

Recursive function to iterative function as binoms

I'm new with algorithms and wonder how this displayed function is supposed to be converted/transformed from recursive to iterative. What should I keep in mind when converting?
public int binom(int n, int k)
{
if (k == 0 || n == k) { return 1; }
return binom(n - 1, k - 1) + binom(n - 1, k);
}
Thanks in advance!
In fact, this problem is not so easy, if you just look at the recursive code and try to decrypt it.
However, it might be a helpful hint for you, that (n over k), i.e. the binomial coefficient can be written as
n! / (k! * (n - k)!)
where "!" denotes the factorial.
And it should be rather easy to compute the factorial in a Loop (i.e. iterative) for you.
If intermediate results are too big you can shorten before computation. You can shorten either term k! or the term (n-k)! (you would choose the bigger one). For example with n = 5 and k = 3 you have:
(1 * 2 * 3 * 4 * 5) / ((1 * 2 * 3) * (1 * 2)) = (4 * 5) / (1 * 2)
Spoiler-Alarm:
public static int binomial(int n, int k) {
int nMinusK = n - k;
if (n < nMinusK) {
//Switch n and nMinusK
int temp = n;
n = nMinusK;
nMinusK = temp;
}
int result = 1;
// n!/k!
for (int i = k + 1; i <= n; i++) {
result *= i;
}
//Division by (n-k)!
for (int j = 1; j <= nMinusK; j++) {
result = result / j;
}
return result;
}
You can use the multiplicative form of binomial coefficients, for example from Wikia, which can be easily implemented with faculties or loops.

Largest prime factor of a number in Java

I am trying to find the Largest prime factor of a number while solving this problem here. I think that I am doing everything right, however one of the test case (#2) is failing and I can't think of any corner case where it might fail. Here's my code, please have a look and try to spot something.
public class ProblemThree
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for (int i = 0; i < T; i++)
{
System.out.println(largestPrime(scanner.nextLong()));
}
}
private static long largestPrime(long n)
{
while (n % 2 == 0)
{
n = n / 2; // remove all the multiples of 2
}
while (n % 3 == 0)
{
n = n / 3; // remove all the multiples of 2
}
// remove multiples of prime numbers other than 2 and 3
while (n >= 5)
{
boolean isDivisionComplete = true;
for (long i = 5; i < Math.ceil(Math.sqrt(n)); i++)
{
if (n % i == 0)
{
n = n / i;
isDivisionComplete = false;
break;
}
}
if (isDivisionComplete)
{
break;
}
}
return n;
}
}
Basically, what I am doing is:
Largest_Prime(n):
1. Repeatedly divide the no by any small number, say x where 0 < x < sqrt(n).
2. Then set n = n/x and repeat steps 1 and 2 until there is no such x that divides n.
3 Return n.
It seems you have some bug in your code as as when you input 16 largestPrime function return 1. and this is true for when input is the power of 3.
Detailed Algorithm description:
You can do this by keeping three variables:
The number you are trying to factor (A)
A current divisor store (B)
A largest divisor store (C)
Initially, let (A) be the number you are interested in - in this case, it is 600851475143. Then let (B) be 2. Have a conditional that checks if (A) is divisible by (B). If it is divisible, divide (A) by (B), reset (B) to 2, and go back to checking if (A) is divisible by (B). Else, if (A) is not divisible by (B), increment (B) by +1 and then check if (A) is divisible by (B). Run the loop until (A) is 1. The (3) you return will be the largest prime divisor of 600851475143.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextLong();
long A=n;
long B=2;
long C=0;
while(Math.pow(B,2)<=A)
{
if(A%B==0)
{
C=B;
A=A/B;
B=2;
}
else
B++;
}
if(A>=C)
C=A;
if(A==1)
{ C=2;
break;
}
System.out.println(C);
}
}
Why are you removing multiples of 2 and multiples of 3? This way if you have a number that is any combination of powers of 2 and 3 you will get your answer as 1 which is clearly wrong.
For this problem you can do the naive way of looping from 2 to sqrt(n) and store the largest number which divides n, when you finish your loop just return the highest divisor you found.
1 drop your loop for 2 and 3. If not, you dont get 2, 2x2, 3, 2x3, ... all multiples of 2 and 3
2 change your loop to stop at 2 (and not 5):
while (n >= 2)
{
3 stop if 2
if (n==2) return 2;
4 loop from 2
and
5 loop until sqrt(n), with <= and not only < (if not, you dont get prime X Prime)
for (long i = 2; i <= Math.ceil(Math.sqrt(n)); i++)
One easy way of extracting prime factors is like this:
/**
* Prime factors of the number - not the most efficient but it works.
*
* #param n - The number to factorise.
* #param unique - Want only unique factors.
* #return - List of all prime factors of n.
*/
public static List<Long> primeFactors(long n, boolean unique) {
Collection<Long> factors;
if (unique) {
factors = new HashSet<>();
} else {
factors = new ArrayList<>();
}
for (long i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return new ArrayList<>(factors);
}
Those first loops are a problem. They will reduce all even numbers to 1 - thus missing 2 as the factor. Changing your code to use:
while (n > 2 && n % 2 == 0) {
n = n / 2; // remove all the multiples of 2
}
while (n > 3 && n % 3 == 0) {
n = n / 3; // remove all the multiples of 2
}
You still have further issues - e.g. you report the largest prime factor of 25 to be 25 and the largest prime factor of 49 to be 49.
Just run this code using yours and mine to see where yours fails:
for (long i = 1; i < 1000; i++) {
long largestPrime = largestPrime(i);
List<Long> primeFactors = primeFactors(i, true);
if (primeFactors.size() > 0) {
Collections.sort(primeFactors, Collections.reverseOrder());
long highestFactor = primeFactors.get(0);
if (largestPrime != highestFactor) {
System.out.println("Wrong! " + i + " " + largestPrime + " != " + primeFactors);
}
} else {
System.out.println("No factors for " + i);
}
}

What is the logic of the recursion

Here is I have a factorial code using recursion.
class Factorial
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println(f.fact(Integer.parseInt(args[0])));
}
private int fact(int num)
{
int result;
if(num == 1)
return 1;
result = fact(num - 1) * num;
return result;
}
}
Now to run this program, I did this
D:\>java Factorial 3
Now according to the logic when it enters the fact function, where num = 3, so it will skip to
result = fact(num - 1) * num;
Here it will become
result = fact(3 - 1) * num;
i.e. result = fact(2) * num;
In this step, I am little confused Does it execute whole step i.e.
result = fact(num - 1) * num;
or just the fact(num - 1)
According to the logic, what it should do is call the fact function. So, the control of the program again reaches to the start of the fact function where num = 2. It will again skip to
result = fact(num - 1) * num;
So, it will become
result = fact(2 - 1) * num;
i.e. result = fact(1) * num;
Now again, it should call the fact function without executing the whole syntax & again reaches to the start of the fact method where num = 1. This time num == 1 will be matched & 1 will be returned. Now it will return to
result = fact(num - 1) * num;
So, it will become
result = fact(1 - 1) * num;
i.e. result = fact(0) * num;
Now what will happen next ?
Am I going right ? If not what will be the correction ?
I dont clearly understand the flow of this recursion program.
So, it will become
result = fact(1 - 1) * num;
Nope. For num = 2,
result = fact(num - 1) * num;
becomes
result = 1 * num; // i.e. 1 * 2
fact returns a value, which means the entire call has to be replace with that value.
Not sure why you would even think num changes at all. You have no num = ... in your code.
I added some trace into the program. Execute it and see the output. Should be easy to follow.
package snippet;
class Factorial {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println(f.fact(Integer.parseInt("5")));
}
private int fact(int num) {
int result;
if (num == 1)
return 1;
result = fact(num - 1) * num;
System.out.println("fact(" + num + ") = " + result + " = fact(" + (num - 1) + ") * " + num);
return result;
}
}
fact(2) = 2 = fact(1) * 2
fact(3) = 6 = fact(2) * 3
fact(4) = 24 = fact(3) * 4
fact(5) = 120 = fact(4) * 5
120
Your logic is right but you have made 3 basic errors.
if we take your example;
First you run the program
D:\>java Factorial 3
then you have your first mistake because according to the logic all "num" have to be replaced by "3". So you get:
result = fact(3 - 1) * 3;
ie:
result = fact(2)*3;
then we have the second mistake because according to the definition of fact(num),
fact(2) = fact(2-1)*2
so we actually have
result = (fact(2-1)*2)*3
which is evaluated in
result = (fact(1)*2)*3
and here stand the third mistake because again according to fact(num) definition : fact(1) = 1 and not fact(1) = fact(1-1)*1
so we finally have:
result = ((1)*2)*3
To be more explicit if you follow all call sequence in the debugger you 'll have something like this( I put between brackets the value of the variable):
private int fact(num{3})
{
int result;
if(num{3}== 1)
return 1;
result = fact(num{3} - 1) * num{3};
private int fact(num{3-1})
{
int result;
if(num{3-1}== 1)
result = fact(num{3-1} - 1) * num{3-1};
private int fact(num{3-1-1})
{
int result;
if(num{3-1-1}== 1)
return 1;
}
return result{1*{3-1}};
}
return result{{1*{3-1}}*3};
}
Unless we hit the stop condition:
fact(num) = fact(num - 1) * num;
Therefore:
fact(3) = fact(3 - 1) * 3;
Keeping in mind that fact(1) = 1 (from the if statement early in the fact() method):
fact(3) = fact(2) * 3;
fact(2) = fact(1) * 2;
fact(1) = 1;
Replacing each element:
fact(3) = 1 * 2 * 3;
The recursion is used to repeatedly dive deeper into the process until a stop condition is encountered - in this case when num = 1.
The call f.fact(3) is expanding through the following steps:
1. result = fact(3 - 1) * 3 = fact(2) * 3
2. result = (fact(2 - 1) * 2) * 3 = (fact(1) * 2) * 3
3. result = 1 * 2 * 3 because fact(1) returns 1.
Your implementation is correct, But it will never reach fact(1-1) * 1 state ,as you return from method at if(num == 1).
num variable is limited to scope of method parameter. So for every call to fact method num variable is assigned a new value (i.e. num-1) and which is limited to that parameter scope only. So when fact(num-1) returns , value of num will be the original value and not the num-1.
The flow of your example is like this
step 1. fact(3)*3; //calling the function with num value 3
step 2. fact(2)*2; //calling fact() method again with num=2
step 3. fact(1)*1; //now num == 1 will be matched & 1 will be returned.
i. e.,
1 * 1 = 1; //now, steps 2 and 1 will be performed respectively
step 2. 1 * 2 = 2;
step 1. 2 * 3 = 6;
So, the final answer will be 6
Note: In step 3, the value is returned, so it will not again call this result = fact(0) * num; //which you have mentioned in question.

Issues while executing Armstrong number program

I am trying out a code that finds out whether a number entered is Armstrong or not. Here is the Code:
import java.util.*;
public class Arm {
int a, b, c;
void m1() {
Scanner obj = new Scanner(System.in);
System.out.println("Enter a number");
int number = obj.nextInt();
number = (100 * a) + (10 * b) + (1 * c);
if ((a * a * a) + (b * b * b) + (c * c * c) == number) {
System.out.println("number is armstrong");
} else {
System.out.println("number is not armstrong");
}
}
public static void main(String args[]) {
Arm obj = new Arm();
obj.m1();
}
}
Here the value of a,b and c comes out to be zero. But that is not the correct result. Say if we enter a number 345. Then a,b and c should be 3, 4 and 5 respectively.
Please guide.
That is not how you calculate a, b, c.
To find a,b,c we repeatedly divide by 10 and get the remainder by modulus.
int digit = 0;
int sum = 0;
while(num > 0)
{
digit = num % 10;
sum += Math.pow(digit, 3);
num = num/10;
}
Why do we use / and %
Consider 345.
Now to get the last digit what can be done?
What does a modulus return? The remainder, so If we perform %10 we get the last digit.
345 % 10 = 5
Now we want the second last digit.
So we divide the number by 10, so we get the quotient
345 / 10 = 34
Now again if we can perform the modulus we get the 4 and so on..
What does 100 * a + 10 * b + 1 * c do?
That is used to get a number if we have the individual digits.
Suppose we have 3, 4, 5 we know that we get 345 out of it but how do we do it?
3 * 100 = 300
4 * 10 = 40
5 * 1 = 5
-----------
300 + 40 + 5 = 345
Now to complete your whole program.
public boolean isAmg(int num)
{
int digit = 0;
int sum = 0;
int copyNum = num; //used to check at the last
while(num > 0)
{
digit = num % 10;
sum += Math.pow(digit, 3);
num = num / 10;
}
return sum == copyNum;
}

Categories

Resources