I am trying to convert this function to use Java 8 new syntax. Hopefully it will reduce the number of lines and perhaps make things clearer.
public int divisorSum(int n) {
int sum = 0;
for(int i = 1; i <= n; i ++) {
if(n % i == 0) {
sum = Integer.sum(sum, i);
}
}
return sum;
}
I tried this:
IntStream.range(0, n).forEach(i -> ... )
But according to a comment on this post by Tezra apparently it is not advisable to loop using lambdas.
Here's the Java 8 streams implementation:
public int divisorSum(int n) {
return IntStream.rangeClosed(1, n).filter(i -> n % i == 0).sum();
}
Note that rangeClosed, like your example, includes n. range() excludes the second parameter (it would only include up to n-1).
You can do something like this
public static int divisorSum(int n) {
return IntStream.rangeClosed(1, n)
.filter(i -> n % i == 0)
.sum();
}
You can achieve the same result using IntStream, filter and IntStream::sum that directly returns int since this stream is unboxed:
int sum = IntStream.rangeClosed(1, n).filter(i -> n % i == 0).sum();
This can be helpful.
int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -> n % x == 0).reduce(0, (x, y) -> x + y);
or
int sum1 = java.util.stream.IntStream.range(1, n + 1).filter(x -> n % x == 0).sum();
Related
i want to transform this function to recursive form could anyone help me thx
that function is to solve this stuff
X=1+(1+2)*2+(1+2+3)*2^2+(1+2+3+4)*2^3+ . . . +(1+2+3+4+. . . +n)*2^(n-1)
public static int calcX(int n) {
int x=1;
int tmp;
for(int i = 1 ; i <= n-1;i++) {
tmp=0;
for(int j = 1 ; j <= i + 1;j++) {
tmp+=j;
}
x+=tmp*Math.pow(2, i);
}
return x;
}
my attempt im new to recursive stuff
public static int calcXrecu(int n,int tmp,int i,int j) {
int x=1;
if(i <= n-1) {
if(j <= i) {
calcXrecu(n,tmp+j,i,j+1);
}
else {
x = (int) (tmp*Math.pow(2, i));
}
}
else {
x=1;
}
return x;
}
You have a sequence of sums which themselves are sums.
The nth term can be derived from the (n-1)th term like this:
a(n) = a(n-1) + (1+2+3+....+n) * 2^(n-1) [1]
and this is the recursive formula because it produces each term via the previous term.
Now you need another formula (high school math) for the sum of 1+2+3+....+n:
1+2+3+....+n = n * (n + 1) / 2 [2]
Now use [2] in [1]:
a(n) = a(n-1) + n * (n + 1) * 2^(n-2) [3]
so you have a formula with which you can derive each term from the previous term and this is all you need for your recursive method:
public static int calcXrecu(int n) {
if (n == 1) return 1;
return calcXrecu(n - 1) + n * (n + 1) * (int) Math.pow(2, n - 2);
}
This line:
if (n == 1) return 1;
is the exit point of the recursion.
Note that Math.pow(2, n - 2) needs to be converted to int because it returns Double.
In addition to #forpas answer, I also want to provide a solution using corecursion by utilizing Stream.iterate. This is obviously not a recursive solution, but I think it is good to know alternatives as well. Note that I use a Pair to represent the tuple of (index, value).
public static int calcXcorecu(final int n) {
return Stream.iterate(
Pair.of(1, 1), p -> {
final int index = p.getLeft();
final int prev = p.getRight();
final int next = prev + index * (index + 1) * (int) Math.pow(2, index - 2);
return Pair.of(index + 1, next);
})
// only need the n-th element
.skip(n)
.limit(1)
.map(Pair::getRight)
.findFirst()
.get();
}
public static int reverse(int n) {
int result = 0;
while (n > 0) {
result = result * 10 + n % 10;
n = n / 10;
}
return result;
}
I'm trying to reverse the digits of integer. Instead of doing the codes like what I have done, is there any other way to do it? Can i reverse it using java stream?
Another way would be
int digits = 12345;
StringBuilder buf = new StringBuilder(String.valueOf(digits));
System.out.println(buf.reverse());
System.out.println(Integer.valueOf(buf.toString()));
OK, here's a fun implementation with IntStream:
public static int reverse (int n) {
return IntStream.iterate (n, i -> i/10) // produces a infinite IntStream of n, n/10,
// n/100, ...
.limit(10) // 10 elements are sufficient, since int has <= 10 digits
.filter (i -> i > 0) // remove any trailing 0 elements
.map(i -> i % 10) // produce an IntStream of the digits in reversed
// order
.reduce (0, (r,i) -> r*10 + i); // reduce the reversed digits back
// to an int
}
For example, for the input 123456789, it will first generate the infinite IntStream:
123456789,12345678,1234567,123456,12345,1234,123,12,1,0,0,...
After limiting to 10 elements and removing the 0s, we are left with:
123456789,12345678,1234567,123456,12345,1234,123,12,1
After mapping each element to its last digit, we get:
9,8,7,6,5,4,3,2,1
Now we just have to reduce the IntStream in a manner similar to what you did in your question - add each element to the intermediate result multiplied by 10:
((((0 * 10 + 9) * 10 + 8) * 10 + 7) * 10 ....) * 10 + 1
Note that if the input number has 10 digits and the last digit > 1, the reversed result will overflow.
It also doesn't support negative input.
One more stream and Math fun implementation.
public static long reverse(int n) {
return Stream.iterate(
Map.entry(0, n % 10),
entry -> Math.pow(10, entry.getKey()) <= n,
entry -> Map.entry(entry.getKey() + 1,
(int) (n % (int) Math.pow(10, entry.getKey() + 2) / Math.pow(10, entry.getKey() + 1))))
.map(Map.Entry::getValue)
.map(Integer::longValue)
.reduce(0L, (r, i) -> r * 10 + i);
}
You should return long in your method, anyway. But StringBuilder is the best here.
A Stream solution which returns for a given number the reversed String:
int n = 10101010;
String reveresed = String.valueOf(n)
.chars()
.mapToObj(Character::getNumericValue)
.reduce("", (l, r) -> r + l, (l, r) -> l + r);
System.out.println(reveresed); // 01010101
If we convert the reversed String to an Integer and print it we will lose the leading zero:
System.out.println(Integer.valueOf(reveresed).toString()); // 1010101
Along with the other answers, you can try this implementation as well.
public class MyStreamReverser {
public static void main(String[] args) {
streamApiReverser(-9008);
// other outputs to test:
// streamApiReverser(20000090);
// streamApiReverser(-04);
// streamApiReverser(39-02);
}
private static void streamApiReverser(int n) {
// produce an array of strings each having one digit
String[] stringArray = String.valueOf(n).split("\\B");
Stream<String> stringStream = Arrays.stream(stringArray);
stringStream.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(System.out::println);
}
}
Output:
8
0
0
-9
Note - Does not play well with leading zeros. 09 doesn't work (since those are treated as octals), works with trailing zeros, should be fine with negatives (but further testing needed).
An easy way to reverse an integer is to parse it into a string, reverse it, and parse it back into a integer.
public static int reverse(int num) {
StringBuffer stringBuffer = new StringBuffer(String.valueOf(num););
stringBuffer.reverse();
return Integer.parseInt(stringBuffer.toString());
}
the quickest answer will be :
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x%10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev*10+pop;
}
return rev;
}
The code works correctly until I give it a big value - it takes too much time to execute.
Can you give me some advice how to optimize it?
BigInteger type of n parameter is a must, it's a part of the task ;)
public static String oddity(BigInteger n) {
List<BigInteger> list = new ArrayList<BigInteger>();
String result = null;
for (BigInteger bi = BigInteger.valueOf(1);
bi.compareTo(n) <= 0;
bi = bi.add(BigInteger.ONE)) {
if (n.mod(bi).equals(BigInteger.ZERO))
list.add(bi);
}
if (list.size() % 2 == 0)
result = "even";
else result = "odd";
return result;
}
The purpose of this is to return 'odd' if the number of "n" divisors is odd. Otherwise return 'even'.
Thinking rather than just programming would help a lot. You don't need to find all divisors. You don't even need to count them. All you need is to find out if the count is odd.
But divisors always come in pairs: For every divisor i also n/i is a divisor.
So the count is always even, except when there's a divisor i equal to n/i. Use Guava sqrt ...
As you don't use the list except to get its final size, you could use an integer as a counter, i.e: do n++ instead of list.add(bi).
This is going to save huge amount of memory. Hence save time used to manage its allocation.
// Lambda
long counter = IntStream
.range(1, (int) Math.sqrt(n.longValue())+1)
.filter(i -> n.longValue() % i == 0 && n.longValue() / i == i)
.count();
return (counter % 2 == 0) ? "even" : "odd";
int counter = 0;
for (long i = 1; i <= Math.sqrt(n.longValue()); i++) {
if(n.longValue() % i == 0 && n.longValue()/ i == i){
counter++;
}
}
return (counter % 2 == 0) ? "even" : "odd";
I need a function which can calculate the mathematical combination of (n, k) for a card game.
My current attempt is to use a function based on usual Factorial method :
static long Factorial(long n)
{
return n < 2 ? 1 : n * Factorial(n - 1);
}
static long Combinatory(long n , long k )
{
return Factorial(n) / (Factorial(k) * Factorial(n - k));
}
It's working very well but the matter is when I use some range of number (n value max is 52 and k value max is 4), it keeps me returning a wrong value. E.g :
long comb = Combinatory(52, 2) ; // return 1 which should be actually 1326
I know that it's because I overflow the long when I make Factorial(52) but the range result I need is not as big as it seems.
Is there any way to get over this issue ?
Instead of using the default combinatory formula n! / (k! x (n - k)!), use the recursive property of the combinatory function.
(n, k) = (n - 1, k) + (n - 1, k - 1)
Knowing that : (n, 0) = 1 and (n, n) = 1.
-> It will make you avoid using factorial and overflowing your long.
Here is sample of implementation you can do :
static long Combinatory(long n, long k)
{
if (k == 0 || n == k )
return 1;
return Combinatory(n - 1, k) + Combinatory(n - 1, k - 1);
}
EDIT : With a faster iterative algorithm
static long Combinatory(long n, long k)
{
if (n - k < k)
k = n - k;
long res = 1;
for (int i = 1; i <= k; ++i)
{
res = (res * (n - i + 1)) / i;
}
return res;
}
In C# you can use BigInteger (I think there's a Java equivalent).
e.g.:
static long Combinatory(long n, long k)
{
return (long)(Factorial(new BigInteger(n)) / (Factorial(new BigInteger(k)) * Factorial(new BigInteger(n - k))));
}
static BigInteger Factorial(BigInteger n)
{
return n < 2 ? 1 : n * Factorial(n - 1);
}
You need to add a reference to System.Numerics to use BigInteger.
If this is not for a homework assignment, there is an efficient implementation in Apache's commons-math package
http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/ArithmeticUtils.html#binomialCoefficientDouble%28int,%20int%29
If it is for a homework assignment, start avoiding factorial in your implementation.
Use the property that (n, k) = (n, n-k) to rewrite your choose using the highest value for k.
Then note that you can reduce n!/k!(n-k)! to n * n-1 * n-2 .... * k / (n-k) * (n-k-1) ... * 1 means that you are multiplying every number from [k, n] inclusive, then dividing by every number [1,n-k] inclusive.
// From memory, please verify correctness independently before trusting its use.
//
public long choose(n, k) {
long kPrime = Math.max(k, n-k);
long returnValue = 1;
for(i = kPrime; i <= n; i++) {
returnValue *= i;
}
for(i = 2; i <= n - kPrime; i++) {
returnValue /= i;
}
return returnValue;
}
Please double check the maths, but this is a basic idea you could go down to get a reasonably efficient implementation that will work for numbers up to a poker deck.
The recursive formula is also known as Pascal's triangle, and IMO it's the easiest way to calculate combinatorials. If you're only going to need C(52,k) (for 0<=k<=52) I think it would be best to fill a table with them at program start. The following C code fills a table using this method:
static int64_t* pascals_triangle( int N)
{
int n,k;
int64_t* C = calloc( N+1, sizeof *C);
for( n=0; n<=N; ++n)
{ C[n] = 1;
for( k=n-1; k>0; --k)
{ C[k] += C[k-1];
}
}
return C;
}
After calling this with N=52, for example returns, C[k] will hold C(52,k) for k=0..52
Is there any other way in Java to calculate a power of an integer?
I use Math.pow(a, b) now, but it returns a double, and that is usually a lot of work, and looks less clean when you just want to use ints (a power will then also always result in an int).
Is there something as simple as a**b like in Python?
When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent
example:
22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead
232 = 1L << 32 = (long) Math.pow(2, 32)
btw. in Kotlin you have shl instead of << so
(java) 1L << 32 = 1L shl 32 (kotlin)
Integers are only 32 bits. This means that its max value is 2^31 -1. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow uses double.
If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.
Best the algorithm is based on the recursive power definition of a^b.
long pow (long a, int b)
{
if ( b == 0) return 1;
if ( b == 1) return a;
if (isEven( b )) return pow ( a * a, b/2); //even a=(a^2)^b/2
else return a * pow ( a * a, b/2); //odd a=a*(a^2)^b/2
}
Running time of the operation is O(logb).
Reference:More information
No, there is not something as short as a**b
Here is a simple loop, if you want to avoid doubles:
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
If you want to use pow and convert the result in to integer, cast the result as follows:
int result = (int)Math.pow(a, b);
Google Guava has math utilities for integers.
IntMath
import java.util.*;
public class Power {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int num = 0;
int pow = 0;
int power = 0;
System.out.print("Enter number: ");
num = sc.nextInt();
System.out.print("Enter power: ");
pow = sc.nextInt();
System.out.print(power(num,pow));
}
public static int power(int a, int b)
{
int power = 1;
for(int c = 0; c < b; c++)
power *= a;
return power;
}
}
Guava's math libraries offer two methods that are useful when calculating exact integer powers:
pow(int b, int k) calculates b to the kth the power, and wraps on overflow
checkedPow(int b, int k) is identical except that it throws ArithmeticException on overflow
Personally checkedPow() meets most of my needs for integer exponentiation and is cleaner and safter than using the double versions and rounding, etc. In almost all the places I want a power function, overflow is an error (or impossible, but I want to be told if the impossible ever becomes possible).
If you want get a long result, you can just use the corresponding LongMath methods and pass int arguments.
Well you can simply use Math.pow(a,b) as you have used earlier and just convert its value by using (int) before it. Below could be used as an example to it.
int x = (int) Math.pow(a,b);
where a and b could be double or int values as you want.
This will simply convert its output to an integer value as you required.
A simple (no checks for overflow or for validity of arguments) implementation for the repeated-squaring algorithm for computing the power:
/** Compute a**p, assume result fits in a 32-bit signed integer */
int pow(int a, int p)
{
int res = 1;
int i1 = 31 - Integer.numberOfLeadingZeros(p); // highest bit index
for (int i = i1; i >= 0; --i) {
res *= res;
if ((p & (1<<i)) > 0)
res *= a;
}
return res;
}
The time complexity is logarithmic to exponent p (i.e. linear to the number of bits required to represent p).
I managed to modify(boundaries, even check, negative nums check) Qx__ answer. Use at your own risk. 0^-1, 0^-2 etc.. returns 0.
private static int pow(int x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
if (n < 0) { // always 1^xx = 1 && 2^-1 (=0.5 --> ~ 1 )
if (x == 1 || (x == 2 && n == -1))
return 1;
else
return 0;
}
if ((n & 1) == 0) { //is even
long num = pow(x * x, n / 2);
if (num > Integer.MAX_VALUE) //check bounds
return Integer.MAX_VALUE;
return (int) num;
} else {
long num = x * pow(x * x, n / 2);
if (num > Integer.MAX_VALUE) //check bounds
return Integer.MAX_VALUE;
return (int) num;
}
}
base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).
public int power(int base, int n){
return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));
}
There some issues with pow method:
We can replace (y & 1) == 0; with y % 2 == 0
bitwise operations always are faster.
Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.
public static long pow(long x, int y) {
long result = 1;
while (y > 0) {
if ((y & 1) == 0) {
x *= x;
y >>>= 1;
} else {
result *= x;
y--;
}
}
return result;
}
Use the below logic to calculate the n power of a.
Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n)
Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).
public int calculatePower1(int a, int b) {
if (b == 0) {
return 1;
}
int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;
int temp = 1;
for (int i = 1; i <= val; i++) {
temp *= a;
}
if (b % 2 == 0) {
return temp * temp;
} else {
return a * temp * temp;
}
}
Apache has ArithmeticUtils.pow(int k, int e).
import java.util.Scanner;
class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
try {
long x = sc.nextLong();
System.out.println(x + " can be fitted in:");
if (x >= -128 && x <= 127) {
System.out.println("* byte");
}
if (x >= -32768 && x <= 32767) {
//Complete the code
System.out.println("* short");
System.out.println("* int");
System.out.println("* long");
} else if (x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) {
System.out.println("* int");
System.out.println("* long");
} else {
System.out.println("* long");
}
} catch (Exception e) {
System.out.println(sc.next() + " can't be fitted anywhere.");
}
}
}
}
int arguments are acceptable when there is a double paramter. So Math.pow(a,b) will work for int arguments. It returns double you just need to cast to int.
int i = (int) Math.pow(3,10);
Without using pow function and +ve and -ve pow values.
public class PowFunction {
public static void main(String[] args) {
int x = 5;
int y = -3;
System.out.println( x + " raised to the power of " + y + " is " + Math.pow(x,y));
float temp =1;
if(y>0){
for(;y>0;y--){
temp = temp*x;
}
} else {
for(;y<0;y++){
temp = temp*x;
}
temp = 1/temp;
}
System.out.println("power value without using pow method. :: "+temp);
}
}
Unlike Python (where powers can be calculated by a**b) , JAVA has no such shortcut way of accomplishing the result of the power of two numbers.
Java has function named pow in the Math class, which returns a Double value
double pow(double base, double exponent)
But you can also calculate powers of integer using the same function. In the following program I did the same and finally I am converting the result into an integer (typecasting). Follow the example:
import java.util.*;
import java.lang.*; // CONTAINS THE Math library
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n= sc.nextInt(); // Accept integer n
int m = sc.nextInt(); // Accept integer m
int ans = (int) Math.pow(n,m); // Calculates n ^ m
System.out.println(ans); // prints answers
}
}
Alternatively,
The java.math.BigInteger.pow(int exponent) returns a BigInteger whose value is (this^exponent). The exponent is an integer rather than a BigInteger. Example:
import java.math.*;
public class BigIntegerDemo {
public static void main(String[] args) {
BigInteger bi1, bi2; // create 2 BigInteger objects
int exponent = 2; // create and assign value to exponent
// assign value to bi1
bi1 = new BigInteger("6");
// perform pow operation on bi1 using exponent
bi2 = bi1.pow(exponent);
String str = "Result is " + bi1 + "^" +exponent+ " = " +bi2;
// print bi2 value
System.out.println( str );
}
}