What does this line of Java stream mean? - java

So I have this line of code. It gives me output [6,28].
Do you guys know why? I dont know what kind of numbers was someone trying to print.
System.out.println( IntStream.range(1,30).filter(n -> IntStream.range(1,n).filter(i->n%i == 0).sum() ==n)
.boxed().collect(Collectors.toList()));

IntStream.range(1,n).filter(i -> n % i == 0).sum() == n
calculates all the divisors of n by checking if n divided by the potential divisor has no remainder (i -> n % i == 0). All divisors are then summed and compared with n itself.
IntStream.range(1,30).filter(n -> ...).boxed().collect(Collectors.toList())
Just does what I described above for the numbers between 1 and 30 and only keeps those where the comparison is true. It therefore calculates all the numbers between 1 and 30 where the divisors sum to the number itself. Those are called perfect numbers. The first two are 6 and 28, followed by 496, ...

Related

Counting n powersets given a list

I am writing a function that determines the number 'n' power sets of a list.
After processing the problem and working through it I found the relationship between the length of the set and the number of powersets.
2^i
where i is the length of the list.
This formula holds true for:
Powers.powers(new int[]{}); // 1
Powers.powers(new int[]{1}); // 2
Powers.powers(new int[]{1,2}); // 4
Powers.powers(new int[]{1,2,3,4}); // 16
Using this information I wrote out the following code:
if(list.length == 1) return BigInteger.valueOf(2);
if(list.length == 0) return BigInteger.valueOf(1);
return BigInteger.valueOf((long)Math.pow(2, list.length));
This works fine for the first few tests, until it hiccups at array length 100. Fortunately it does calculate the correct value that being 1.2676506e+30, but the expected number of powersets of Arraysize 100 is: 9223372036854775807.
Edit:
Adjusted the formula to 2^i, and to clarify I understand how the calculation works, I just don't understand how or why the test case expects 9223372036854775807. It passes an array of length 100 with all values being 0 except for value of index 99 being 100.
You mean 2 ^ n, not 4 ^ (n/2). Well, it's actually the same thing.
And it is very easily calculated with BigInteger, without risk of overflow:
static BigInteger powerSets(int n) {
return BigInteger.ONE.shiftLeft(n);
}
Test
System.out.println(powerSets(0));
System.out.println(powerSets(1));
System.out.println(powerSets(2));
System.out.println(powerSets(4));
System.out.println(powerSets(100));
System.out.println(powerSets(1000));
Output
1
2
4
16
1267650600228229401496703205376
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
UPDATE: If there can be duplicate values, it becomes slightly more complex:
static BigInteger powers(int... values) {
return Arrays.stream(values).boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.values().stream()
.map(freq -> BigInteger.valueOf(freq + 1))
.reduce(BigInteger.ONE, BigInteger::multiply);
}
Test
System.out.println(powers());
System.out.println(powers(1));
System.out.println(powers(1,2));
System.out.println(powers(1,2,3,4));
System.out.println(powers(0,1,2,3,4,5,6,7,8,9,
10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29,
30,31,32,33,34,35,36,37,38,39,
40,41,42,43,44,45,46,47,48,49,
50,51,52,53,54,55,56,57,58,59,
60,61,62,63,64,65,66,67,68,69,
70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,
90,91,92,93,94,95,96,97,98,99));
System.out.println(powers(1,3,3,3,3,7));
Output
1
2
4
16
1267650600228229401496703205376
20

Getting wrong answer on codechef.But my math is right

Link of the question-https://www.codechef.com/problems/MATPH
So , I'm stuck on this question for hours and I don't know where I'm wrong.
I have used Sieve of Eratosthenes for finding prime and I saved all prime numbers in hash map.Online judge is giving me wrong answer on test cases.
static void dri(int n) {
long large=0;int r=0,x,count=0,p,count1=0;
x=(int)Math.sqrt(n);
//To understand why I calculated x let's take an example
//let n=530 sqrt(530) is 23 so for all the numbers greater than 23 when
//we square them they will come out to be greater than n
//so now I just have to check the numbers till x because numbers
//greater than x will defiantly fail.I think you get
//what I'm trying to explain
while(r<x) {
r = map.get(++count); // Prime numbers will be fetched from map and stored in r
int exp = (int) (Math.log(n) / Math.log(r));
//To explain this line let n=64 and r=3.Now, exp will be equal to 3
//This result implies that for r=3 the 3^exp is the //maximum(less than n) value which I can calculate by having a prime in a power
if (exp != 1) { //This is just to resolve an error dont mind this line
if (map.containsValue(exp) == false) {
//This line implies that when exp is not prime
//So as I need prime number next lines of code will calculate the nearest prime to exp
count1 = exp;
while (!map.containsValue(--count1)) ;
exp = count1;
}
int temp = (int) Math.pow(r, exp);
if (large < temp)
large = temp;
}
}
System.out.println(large);
}
I
For each testcase, output in a single line containing the largest
beautiful number ≤ N. Print −1 if no such number exists.
I believe that 4 is the smallest beautiful number since 2 is the smallest prime number and 2^2 equals 4. N is just required to ≥ 0. So dri(0), dri(1), dri(2) and dri(3) should all print −1. I tried. They don’t. I would believe that this is the reason for your failure on CodeChef.
I am leaving it to yourself to find out how the mentioned calls to your method behave and what to do about it.
As an aside, what’s the point in keeping your prime numbers in a map? Wouldn’t a list or a sorted set be more suitable?

find a number in another number without using Array

Recently i attended an interview where i was asked to write a function to find a term in a number and the number of times it occurs.
Lets say term = 51, number = 164518351, so 51 does exits in number and it occurs for 2 times, so return 2.
My Solution - Convert the number and term into string and , replace term string with "A" in the number string and then finally count the number of "A" in the number string. He asked me to solve without using strings, so i gave an array approach.
But he said that i cannot use arrays as well. so i want to know if there are other ways to do this ? I don't want the exact code or algo i just want to know various approaches we can take to solve this problem in minimum time complexity.
you can try something like this
int term_count = 0;
while(number > 0){
if(number % 100 == term)
term_count++;
number = number/10
}
This will check if the last two digits of the number is equal to the term, and continue doing so ignoring every unit digits of the number.
something like this
164518351 % 100 == 51
16451835 % 100 == 51
1645183 % 100 == 51
164518 % 100 == 51
....
of course, here i know that the term is two digits and so i mod by 100. if you don't know that, you can find the number of digits in the term and then mod number by
10^(num_of_digits_in_term)
you can find the number of digits like this
int tempTerm = term, termDigitCount = 0;
while(tempTerm > 0){
termDigitCount++;
tempTerm /= 10;
}
// 51 > 0 -> termDigitCount = 1
// 1 > 0 -> termDigitCount = 2
// 0 > 0 -> exit while loop
and in the end if the term_count is 0, then there is no occurrence of the term in the number
Hope this helps.
P.S - the solution may not be syntactically correct since OP does not want an exact answer. just the logic.

how a splitting number to a separate digits algorithm works

i'm getting back to software development and i was playing around with algorithms in java,and today i'm doing the algorithm the splits a number to a separate digits, I've found it here i wrote it in java ..it works but honestly i don't how ?? there is the code just i didn't understand a part of it :
public static void main(String[] args) {
Integer test = 0, i, N;
ArrayList array_one= new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
System.out.print("Write An Integer :");
test = sc.nextInt();
while (test > 0){
int mod = test % 10; // <= DON'T UNDERSTAND THE WORK OF THAT PART
// (i know it's the modulo of the entered value)
test = test / 10;
array_one.add(mod);
}
System.out.print(array_one);
}
i know it's a newbie question i'm just passionate about software engineering and algorithms just want to know how it exactly works and thks in advance.
test % 10; gives you the last (least significant) digit of the number, which is the remainder when dividing the number by 10.
test = test / 10 reduces the number by one digit (123456 becomes 12345), making the former 2nd least significant digit the new least significant digit. Therefore, in the next iteration, test % 10; would return the 2nd digit.
And so on...
test % 10; --> Always gives you the last digit.
test / 10; --> divides the existing number by 10.
while loop --> executes until test > 0
So, if your number is 234,
234%10 would be 4
234/10 would be 23.4 which will be converted to 23.
Apply 23 % 10 and 23/10 and so on..
By using %10 you'll get only the last digit.
/10 will give what is before your last digit.
And so you can construct your array.
124%10 --> 4
124/10 --> 12 % 10 --> 2
12 / 10 --> 1
The logic used here is to separate the units place first by dividing the number by 10 and getting the reminder value.
e.g x=153
"% " is the modulus operator that gives the remainder of the division
"/" is the division operator that gives only the quotient
then 153%10= 3 //this is the remainder that separates the first digit.
The number is then divided by 10 so as to get the quotient
i.e 153/10 =15 // Only the quotient
Progressing with the loop, now 15 is taken as the new original number and is again divided by 10 to get the remainder and hence the next digit.
i.e 15%10 =5 //next digit
15/10=1;
1%10=1 //digit
1/10=0 //The loop ends here
You can understand it by an example
Your number to divide it's digits is 345
If you divide it by 10 your remaining and first digit is 5

Find multiple of a number that can be written with 1s and 0s

Given the number n (2 <= n <= 1000), find the lowest nonzero multiple of which is written in base 10 with digits 0 and 1 only. Examples: 2 -> 10, 3 -> 111, 4 -> 100, 7 -> 1001, 11 -> 11, 9 -> 111 111 111.
My idea is not very good:
{/* n|2 and n|5 +"000"(max for apparition(2,5)) ->
n|3 + "111 " */}
I think, follow the remaining division of numbers consist of numbers n which is formatted 0/1.
Thanks for your help!
You can use a breadth first search. Start by enqueing 1, since your number must start with a 1, then each time you extract a number x from your queue, see if it's a multiple of n or not. If yes, you have your answer, if not insert x * 10 and x * 10 + 1 in the queue (in that order).
Note that you do not actually have to store the entire strings of 1s and 0s in your queue: it's enough to store the remainder of division by n and some auxiliary information that lets you reconstruct the actual string. Write back if you need more details about this.
The non-bruteforce approach would be to iterate throught the series of numbers that contain only 0 and 1 then figure out if the number is a multiple of the number in question. This approach will be substantially more efficient than iterating through the multiples of n and determining if it contains only 0 and 1.
IVlad's suggestion is the more efficient way to produce the series (numbers that contain only 0 and 1). However, if you prefer to generate the numbers on-the-fly (no memory overheads of the queue) you can simply iterate through the integers (or use your loop index) and for each value interpret its binary representation as a decimal number.
2 (Decimal) -> 10 (Binary) -> (interpret as decimal 10)
3 (Decimal) -> 11 (Binary) -> (interpret as decimal 11)
4 (Decimal) -> 100 (Binary) -> (interpret as decimal 100)
5 (Decimal) -> 101 (Binary) -> (interpret as decimal 101)
... and so on.
For the conversion, I suspect it can be done by chaining calls to Integer.toBinaryString() and String.parseInt() but there may well be more efficient ways to do that.
Here's an online demo to get you started: http://jsfiddle.net/6j5De/4/
public static int result(int num)
{
int i =2;
while(true)
{
int mult = Integer.parseInt(Integer.toString(i++,2));
if( mult % num == 0) //Check whether it is a multipler of given number or not ?
{
return mult;
}
}
}

Categories

Resources