How do I generate Primes Using 6*k +- 1 rule - java

We know that all primes above 3 can be generated using:
6 * k + 1
6 * k - 1
However we all numbers generated from the above formulas are not prime.
For Example:
6 * 6 - 1 = 35 which is clearly divisible by 5.
To Eliminate such conditions, I used a Sieve Method and removing the numbers which are factors of the numbers generated from the above formula.
Using the facts:
A number is said to be prime if it has no prime factors.
As we can generate all the prime numbers using the above formulas.
If we can remove all the multiples of the above numbers we are left with only prime numbers.
To generate primes below 1000.
ArrayList<Integer> primes = new ArrayList<>();
primes.add(2);//explicitly add
primes.add(3);//2 and 3
int n = 1000;
for (int i = 1; i <= (n / 6) ; i++) {
//get all the numbers which can be generated by the formula
int prod6k = 6 * i;
primes.add(prod6k - 1);
primes.add(prod6k + 1);
}
for (int i = 0; i < primes.size(); i++) {
int k = primes.get(i);
//remove all the factors of the numbers generated by the formula
for(int j = k * k; j <= n; j += k)//changed to k * k from 2 * k, Thanks to DTing
{
int index = primes.indexOf(j);
if(index != -1)
primes.remove(index);
}
}
System.out.println(primes);
However, this method does generate the prime numbers correctly. This runs in a much faster way as we need not check for all the numbers which we do check in a Sieve.
My question is that am I missing any edge case? This would be a lot better but I never saw someone using this. Am I doing something wrong?
Can this approach be much more optimized?
Taking a boolean[] instead of an ArrayList is much faster.
int n = 100000000;
boolean[] primes = new boolean[n + 1];
for (int i = 0; i <= n; i++)
primes[i] = false;
primes[2] = primes[3] = true;
for (int i = 1; i <= n / 6; i++) {
int prod6k = 6 * i;
primes[prod6k + 1] = true;
primes[prod6k - 1] = true;
}
for (int i = 0; i <= n; i++) {
if (primes[i]) {
int k = i;
for (int j = k * k; j <= n && j > 0; j += k) {
primes[j] = false;
}
}
}
for (int i = 0; i <= n; i++)
if (primes[i])
System.out.print(i + " ");

5 is the first number generated by your criteria. Let's take a look at the numbers generated up to 25:
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25
Now, let's look at these same numbers, when we use the Sieve of Eratosthenes algorithm:
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25
After removing 2:
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25
After removing 3:
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25
This is the same as the first set! Notice they both include 25, which is not prime. If we think about it, this is an obvious result. Consider any group of 6 consecutive numbers:
6k - 3, 6k - 2, 6k - 1, 6k, 6k + 1, 6k + 2
If we factor a little, we get:
3*(2k - 1), 2*(3k - 1), 6k - 1, 6*(k), 6k + 1, 2*(3k + 1)
In any group of 6 consecutive numbers, three of them will be divisible by two, and two of them will be divisible by three. These are exactly the numbers we have removed so far! Therefore:
Your algorithm to only use 6k - 1 and 6k + 1 is exactly the same as the first two rounds of the Sieve of Erathosthenes.
It's a pretty nice speed improvement over the Sieve, too, because we don't have to add all those extra elements just to remove them. This explains why your algorithm works and why it doesn't miss any cases; because it's exactly the same as the Sieve.
Anyway, I agree that once you've generated primes, your boolean way is by far the fastest. I have set up a benchmark using your ArrayList way, your boolean[] way, and my own way using LinkedList and iterator.remove() (because removals are fast in a LinkedList. Here's the code for my test harness. Note that I run the test 12 times to ensure that the JVM is warmed up, and I print the size of the list and change the size of n to attempt to prevent too much branch prediction optimization. You can also get faster in all three methods by using += 6 in the initial seed, instead of prod6k:
import java.util.*;
public class PrimeGenerator {
public static List<Integer> generatePrimesArrayList(int n) {
List<Integer> primes = new ArrayList<>(getApproximateSize(n));
primes.add(2);// explicitly add
primes.add(3);// 2 and 3
for (int i = 6; i <= n; i+=6) {
// get all the numbers which can be generated by the formula
primes.add(i - 1);
primes.add(i + 1);
}
for (int i = 0; i < primes.size(); i++) {
int k = primes.get(i);
// remove all the factors of the numbers generated by the formula
for (int j = k * k; j <= n; j += k)// changed to k * k from 2 * k, Thanks
// to DTing
{
int index = primes.indexOf(j);
if (index != -1)
primes.remove(index);
}
}
return primes;
}
public static List<Integer> generatePrimesBoolean(int n) {
boolean[] primes = new boolean[n + 5];
for (int i = 0; i <= n; i++)
primes[i] = false;
primes[2] = primes[3] = true;
for (int i = 6; i <= n; i+=6) {
primes[i + 1] = true;
primes[i - 1] = true;
}
for (int i = 0; i <= n; i++) {
if (primes[i]) {
int k = i;
for (int j = k * k; j <= n && j > 0; j += k) {
primes[j] = false;
}
}
}
int approximateSize = getApproximateSize(n);
List<Integer> primesList = new ArrayList<>(approximateSize);
for (int i = 0; i <= n; i++)
if (primes[i])
primesList.add(i);
return primesList;
}
private static int getApproximateSize(int n) {
// Prime Number Theorem. Round up
int approximateSize = (int) Math.ceil(((double) n) / (Math.log(n)));
return approximateSize;
}
public static List<Integer> generatePrimesLinkedList(int n) {
List<Integer> primes = new LinkedList<>();
primes.add(2);// explicitly add
primes.add(3);// 2 and 3
for (int i = 6; i <= n; i+=6) {
// get all the numbers which can be generated by the formula
primes.add(i - 1);
primes.add(i + 1);
}
for (int i = 0; i < primes.size(); i++) {
int k = primes.get(i);
for (Iterator<Integer> iterator = primes.iterator(); iterator.hasNext();) {
int primeCandidate = iterator.next();
if (primeCandidate == k)
continue; // Always skip yourself
if (primeCandidate == (primeCandidate / k) * k)
iterator.remove();
}
}
return primes;
}
public static void main(String... args) {
int initial = 4000;
for (int i = 0; i < 12; i++) {
int n = initial * i;
long start = System.currentTimeMillis();
List<Integer> result = generatePrimesArrayList(n);
long seconds = System.currentTimeMillis() - start;
System.out.println(result.size() + "\tArrayList Seconds: " + seconds);
start = System.currentTimeMillis();
result = generatePrimesBoolean(n);
seconds = System.currentTimeMillis() - start;
System.out.println(result.size() + "\tBoolean Seconds: " + seconds);
start = System.currentTimeMillis();
result = generatePrimesLinkedList(n);
seconds = System.currentTimeMillis() - start;
System.out.println(result.size() + "\tLinkedList Seconds: " + seconds);
}
}
}
And the results of the last few trials:
3432 ArrayList Seconds: 430
3432 Boolean Seconds: 0
3432 LinkedList Seconds: 90
3825 ArrayList Seconds: 538
3824 Boolean Seconds: 0
3824 LinkedList Seconds: 81
4203 ArrayList Seconds: 681
4203 Boolean Seconds: 0
4203 LinkedList Seconds: 100
4579 ArrayList Seconds: 840
4579 Boolean Seconds: 0
4579 LinkedList Seconds: 111

You don't need to add all possible candidates to the array. You can create a Set to store all non primes.
Also you can start checking at k * k, rather than 2 * k
public void primesTo1000() {
Set<Integer> notPrimes = new HashSet<>();
ArrayList<Integer> primes = new ArrayList<>();
primes.add(2);//explicitly add
primes.add(3);//2 and 3
for (int i = 1; i < (1000 / 6); i++) {
handlePossiblePrime(6 * i - 1, primes, notPrimes);
handlePossiblePrime(6 * i + 1, primes, notPrimes);
}
System.out.println(primes);
}
public void handlePossiblePrime(
int k, List<Integer> primes, Set<Integer> notPrimes) {
if (!notPrimes.contains(k)) {
primes.add(k);
for (int j = k * k; j <= 1000; j += k) {
notPrimes.add(j);
}
}
}
untested code, check corners
Here is a bit packing version of the sieve as suggested in the answer referenced by #Will Ness. Rather than return the nth prime, this version returns a list of primes to n:
public List<Integer> primesTo(int n) {
List<Integer> primes = new ArrayList<>();
if (n > 1) {
int limit = (n - 3) >> 1;
int[] sieve = new int[(limit >> 5) + 1];
for (int i = 0; i <= (int) (Math.sqrt(n) - 3) >> 1; i++)
if ((sieve[i >> 5] & (1 << (i & 31))) == 0) {
int p = i + i + 3;
for (int j = (p * p - 3) >> 1; j <= limit; j += p)
sieve[j >> 5] |= 1 << (j & 31);
}
primes.add(2);
for (int i = 0; i <= limit; i++)
if ((sieve[i >> 5] & (1 << (i & 31))) == 0)
primes.add(i + i + 3);
}
return primes;
}
There seems to be a bug in your updated code that uses a boolean array (it is not returning all the primes).
public static List<Integer> booleanSieve(int n) {
boolean[] primes = new boolean[n + 5];
for (int i = 0; i <= n; i++)
primes[i] = false;
primes[2] = primes[3] = true;
for (int i = 1; i <= n / 6; i++) {
int prod6k = 6 * i;
primes[prod6k + 1] = true;
primes[prod6k - 1] = true;
}
for (int i = 0; i <= n; i++) {
if (primes[i]) {
int k = i;
for (int j = k * k; j <= n && j > 0; j += k) {
primes[j] = false;
}
}
}
List<Integer> primesList = new ArrayList<>();
for (int i = 0; i <= n; i++)
if (primes[i])
primesList.add(i);
return primesList;
}
public static List<Integer> bitPacking(int n) {
List<Integer> primes = new ArrayList<>();
if (n > 1) {
int limit = (n - 3) >> 1;
int[] sieve = new int[(limit >> 5) + 1];
for (int i = 0; i <= (int) (Math.sqrt(n) - 3) >> 1; i++)
if ((sieve[i >> 5] & (1 << (i & 31))) == 0) {
int p = i + i + 3;
for (int j = (p * p - 3) >> 1; j <= limit; j += p)
sieve[j >> 5] |= 1 << (j & 31);
}
primes.add(2);
for (int i = 0; i <= limit; i++)
if ((sieve[i >> 5] & (1 << (i & 31))) == 0)
primes.add(i + i + 3);
}
return primes;
}
public static void main(String... args) {
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
for (int i = 0; i < 10; i++) {
int n = (int) Math.pow(10, i);
Stopwatch timer = Stopwatch.createUnstarted();
timer.start();
List<Integer> result = booleanSieve(n);
timer.stop();
System.out.println(result.size() + "\tBoolean: " + timer);
}
for (int i = 0; i < 10; i++) {
int n = (int) Math.pow(10, i);
Stopwatch timer = Stopwatch.createUnstarted();
timer.start();
List<Integer> result = bitPacking(n);
timer.stop();
System.out.println(result.size() + "\tBitPacking: " + timer);
}
});
}
0 Boolean: 38.51 μs
4 Boolean: 45.77 μs
25 Boolean: 31.56 μs
168 Boolean: 227.1 μs
1229 Boolean: 1.395 ms
9592 Boolean: 4.289 ms
78491 Boolean: 25.96 ms
664116 Boolean: 133.5 ms
5717622 Boolean: 3.216 s
46707218 Boolean: 32.18 s
0 BitPacking: 117.0 μs
4 BitPacking: 11.25 μs
25 BitPacking: 11.53 μs
168 BitPacking: 70.03 μs
1229 BitPacking: 471.8 μs
9592 BitPacking: 3.701 ms
78498 BitPacking: 9.651 ms
664579 BitPacking: 43.43 ms
5761455 BitPacking: 1.483 s
50847534 BitPacking: 17.71 s

There are several things that could be optimized.
For starters, the "contains" and "removeAll" operations on an ArrayList are rather expensive operations (linear for the former, worst case quadratic for the latter) so you might not want to use the ArrayList for this. A Hash- or TreeSet has better complexities for this, being nearly constant (Hashing complexities are weird) and logarithmic I think
You could look into the sieve of sieve of Eratosthenes if you want a more efficient sieve altogeter, but that would be besides the point of your question about the 6k +-1 trick. It is slightly but not noticably more memory expensive than your solution, but way faster.

Can this approach be much more optimized?
The answer is yes.
I'll start by saying that it is a good idea to use the sieve on a subset of number within a certain range, and your suggesting is doing exactly that.
Reading about generating Primes:
...Furthermore, based on the sieve formalisms, some integer sequences
(sequence A240673 in OEIS) are constructed which they also could be used for generating primes in certain intervals.
The meaning of this paragraph is that your approach of starting with a reduced list of integers was indeed adopted by the academy, but their techniques are more efficient (but also, naturally, more complex).

You can generate your trial numbers with a wheel, adding 2 and 4 alternately, that eliminates the multiplication in 6 * k +/- 1.
public void primesTo1000() {
Set<Integer> notPrimes = new HashSet<>();
ArrayList<Integer> primes = new ArrayList<>();
primes.add(2); //explicitly add
primes.add(3); //2 and 3
int step = 2;
int num = 5 // 2 and 3 already handled.
while (num < 1000) {
handlePossiblePrime(num, primes, notPrimes);
num += step; // Step to next number.
step = 6 - step; // Step by 2, 4 alternately.
}
System.out.println(primes);
}

Probably the most suitable standard datastructure for Sieve of Eratosthenes is the BitSet. Here's my solution:
static BitSet genPrimes(int n) {
BitSet primes = new BitSet(n);
primes.set(2); // add 2 explicitly
primes.set(3); // add 3 explicitly
for (int i = 6; i <= n ; i += 6) { // step by 6 instead of multiplication
primes.set(i - 1);
primes.set(i + 1);
}
int max = (int) Math.sqrt(n); // don't need to filter multiples of primes bigger than max
// this for loop enumerates all set bits starting from 5 till the max
// sieving 2 and 3 is meaningless: n*6+1 and n*6-1 are never divisible by 2 or 3
for (int i = primes.nextSetBit(5); i >= 0 && i <= max; i = primes.nextSetBit(i+1)) {
// The actual sieve algorithm like in your code
for(int j = i * i; j <= n; j += i)
primes.clear(j);
}
return primes;
}
Usage:
BitSet primes = genPrimes(1000); // generate primes up to 1000
System.out.println(primes.cardinality()); // print number of primes
// print all primes like {2, 3, 5, ...}
System.out.println(primes);
// print all primes one per line
for(int prime = primes.nextSetBit(0); prime >= 0; prime = primes.nextSetBit(prime+1))
System.out.println(prime);
// print all primes one per line using java 8:
primes.stream().forEach(System.out::println);
The boolean-based version may work faster for small n values, but if you need, for example, a million of prime numbers, BitSet will outperform it in several times and actually works correctly. Here's lame benchmark:
public static void main(String... args) {
long start = System.nanoTime();
BitSet res = genPrimes(10000000);
long diff = System.nanoTime() - start;
System.out.println(res.cardinality() + "\tBitSet Seconds: " + diff / 1e9);
start = System.nanoTime();
List<Integer> result = generatePrimesBoolean(10000000); // from durron597 answer
diff = System.nanoTime() - start;
System.out.println(result.size() + "\tBoolean Seconds: " + diff / 1e9);
}
Output:
664579 BitSet Seconds: 0.065987717
664116 Boolean Seconds: 0.167620323
664579 is the correct number of primes below 10000000.

This method below shows how to find prime nos using 6k+/-1 logic
this was written in python 3.6
def isPrime(n):
if(n<=1):
return 0
elif(n<4): #2 , 3 are prime
return 1
elif(n%2==0): #already excluded no.2 ,so any no. div. by 2 cant be prime
return 0
elif(n<9): #5, 7 are prime and 6,8 are excl. in the above step
return 1
elif(n%3==0):
return 1
f=5 #Till now we have checked the div. of n with 2,3 which means with 4,6,8 also now that is why f=5
r=int(n**.5) #rounding of root n, i.e: floor(sqrt(n)) r*r<=n
while(f<=r):
if(n%f==0): #checking if n has any primefactor lessthan sqrt(n), refer LINE 1
return 0
if(n%(f+2)==0): #remember her we are not incrementing f, see the 6k+1 rule to understand this while loop steps ,you will see that most values of f are prime
return 0
f=f+6
return 1
def prime_nos():
counter=2 #we know 2,3 are prime
print(2)
print(3) #we know 2,3 are prime
i=1
s=5 #sum 2+3
t=0
n=int(input("Enter the upper limit( should be > 3: "))
n=(n-1)//6 #finding max. limit(n=6*i+1) upto which I(here n on left hand side) should run
while(i<n):#2*(10**6)):
if (isPrime(6*i-1)):
counter=counter+1
print(6*i-1) #prime no
if(isPrime(6*i+1)):
counter=counter+1
print(6*i+1) #prime no
i+=1
prime_nos() #fn. call

Your prime number formula mathematically incorrect ex. take 96 it dividable to 6 96/6=16 so by this logic 97 and 95 must be prime if square root passed but square root of 95 is 9.7467... (passed) so its "prime". But 95 clearly dividable by 5 fast algorithm in c#
int n=100000000;
bool [] falseprimes = new bool[n + 2];
int ed=n/6;
ed = ed * 6;
int md = (int)Math.Sqrt((double)ed);
for (int i = ed; i > md; i-=6)
{
falseprimes[i + 1] = true;
falseprimes[i - 1] = true;
}
md = md / 6;
md = md * 5;
for (int i = md; i > 5; i -= 6)
{
falseprimes[i + 1] = true;
falseprimes[i - 1] = true;
falseprimes[(i + 1)* (i + 1)] = false;
falseprimes[(i-1) * (i-1)] = false;
}
falseprimes[2] = true;
falseprimes[3] = true;

To generate prime numbers using 6 * k + - 1 rule use this algorithm:
int n = 100000000;
int j,jmax=n/6;
boolean[] primes5m6 = new boolean[jmax+1];
boolean[] primes1m6 = new boolean[jmax+1];
for (int i = 0; i <= jmax; i++){
primes5m6[i] = false;
primes1m6[i] = false;
}
for (int i = 1; i <= (int)((Math.sqrt(n)+1)/6)+1; i++){
if (!primes5m6[i]){
for (j = 6*i*i; j <= jmax; j+=6*i-1){
primes5m6[j]=true;
primes1m6[j-2*i]=true;
}
for (; j <= jmax+2*i; j+=6*i-1)
primes1m6[j-2*i]=true;
}
if (!primes1m6[i]){
for (j = 6*i*i; j <= jmax-2*i; j+=6*i+1){
primes5m6[j]=true;
primes1m6[j+2*i]=true;
}
for (; j <= jmax; j+=6*i+1)
primes5m6[j]=true;
}
}
System.out.print(2 + " ");
System.out.print(3 + " ");
for (int i = 1; i <= jmax; i++){
if (!primes5m6[i])
System.out.print((6*i-1) + " ");
if (!primes1m6[i])
System.out.print((6*i+1) + " ");
}

Related

Get the maximum possible value after doing an addition

My program takes a number and checks each digit, adds a 5 to it and generates a modified number. Now find the maximum modified value as result.
Example:
Input:
555
Output:
5510
Explanation:
All possible combinations are :
1055
5105
5510
Maximum in these is 5510.
Example:
Input : 444, output : 944.
Constraints: input number can range from 0 to 100000.
This is my code which is working for this example.
public static int process(int number) {
int n = number;
List<Integer> list = new ArrayList<>();
if (n == 0)
return 5;
while (n > 0) {
list.add(n % 10);
n /= 10;
}
int out = -1;
for (int i = list.size() - 1; i >= 0; i--) {
StringBuilder sb = new StringBuilder();
for (int j = list.size() - 1; j >= 0; j--) {
int e = list.get(j);
if (i == j) {
e += 5;
}
sb.append(e);
}
out = Math.max(out, Integer.parseInt(sb.toString()));
}
return out;
}
How to improve this code by reducing time complexity.
If the number has any digits >= 5, choose the right-most such digit. Otherwise choose the left-most digit.
We must choose a digit >= 5 if such exists because that buys us an extra digit and grows the number by more vs any digit < 5 which doesn't get us an extra digit. We choose the right-most because our new number will be 1x and we want that 1 as far to the right as possible.
If all digits are < 5 then +5 will just increase whichever digit it's applied do, which we want done to our left-most digit.
So linear time in the number of digits: scan the digits for ones >= 5, and either modify the last such you find, or the first digit if you find none.
A solution without char/String/StringBuilder may look like this:
use a flag found5 to detect the first occurrence of a digit >= 5
when a first digit >= 5 is detected, add 5, reset the flag, and use additional shift of a power
in the main loop body, calculate the result by adding power * digit, divide n by 10, multiply power by 10 * shift
when the loop is done, check for the flag and add 5 to the leftmost digit
private static int numAnd5(int n) {
boolean found5 = false;
int result = 0;
int power = 1;
while (n > 0) {
int shift = 1;
int digit = n % 10;
if (!found5 && digit >= 5) {
found5 = true;
digit += 5;
shift = 10;
}
result += power * digit;
power *= 10 * shift;
n /= 10;
}
if (!found5) {
result += 5 * Math.max(1, power / 10);
}
return result;
}
Tests:
for (int x : new int[]{0, 1, 2, 7, 10, 14, 16, 61, 125, 153, 111, 145071, 4321023 }) {
System.out.println(x + " -> " + numAnd5(x));
}
Output:
0 -> 5
1 -> 6
2 -> 7
7 -> 12
10 -> 60
14 -> 64
16 -> 111
61 -> 111
125 -> 1210
153 -> 1103
111 -> 611
145071 -> 1450121
4321023 -> 9321023
The following should reduce it from O(n^2) to O(n) where n is the number of characters in the input.
Note that I do not know Java and do not have access to an IDE at the moment, so the following is untested C#/Java-like pseudocode:
public static int process(int number) {
int n = number;
List<Integer> list = new ArrayList<>();
if (n == 0)
return 5;
while (n > 0) {
list.add(n % 10);
n /= 10;
}
// convenient list of powers of 10
List<Integer> powers = new ArrayList<>(list.size);
n = 1;
for (int i = powers.size() - 1; i >= 0; i--) {
powers[i] = n;
n *= 10;
}
int out = -1;
int top = 0;
int bottom = number;
for (int i = list.size() - 1; i >= 0; i--) {
//StringBuilder sb = new StringBuilder();
int curr = list[i] * power[i];
bottom -= curr;
int newTop = top;
int newCurr = (list[i]+5) * power[i];
if (list[i]+5 > 9) {
newTop *= 10;
}
out = Math.max(out, newTop + newCurr + bottom);
top += curr;
}
return out;
}

Select two equally-sized disjoint subarrays, A and B, that maximise the sum (A_1*B_k + A_2*B_(k-1) ... + A_k*B_1), k = |A| = |B|

A food fest is organised at the JLN stadium. The stalls from different states and cities have been set up. To make the fest more interesting, multiple games have been arranged which can be played by the people to win the food vouchers.One such game to win the food vouchers is described below:
There are N number of boxes arranged in a single queue. Each box has an integer I written on it. From the given queue, the participant has to select two contiguous subsequences A and B of the same size. The selected subsequences should be such that the summation of the product of the boxes should be maximum. The product is not calculated normally though. To make the game interesting, the first box of subsequence A is to be multiplied by the last box of subsequence B. The second box of subsequence A is to be multiplied by the second last box of subsequence B and so on. All the products thus obtained are then added together.
If the participant is able to find the correct such maximum summation, he/she will win the game and will be awarded the food voucher of the same value.
Note: The subsequences A and B should be disjoint.
Example:
Number of boxes, N = 8
The order of the boxes is provided below:
1 9 2 3 0 6 7 8
Subsequence A
9 2 3
Subsequence B
6 7 8
The product of the subsequences will be calculated as below:
P1 = 9 * 8 = 72
P2 = 2 * 7 = 14
P3 = 3 * 6 = 18
Summation, S = P1 + P2 + P3 = 72 + 14 + 18 = 104
This is the maximum summation possible as per the requirement for the given N boxes.
Tamanna is also in the fest and wants to play this game. She needs help in winning the game and is asking for your help. Can you help her in winning the food vouchers?
Input Format
The first line of input consists of the number of boxes, N.
The second line of input consists of N space-separated integers.
Constraints
1< N <=3000
-10^6 <= I <=10^6
Output Format
Print the maximum summation of the product of the boxes in a separate line.
Sample TestCase 1
input
8
1 9 2 3 0 6 7 8
output
104
my code is this it is passing only one test can anyone tell me what is wrong and i don't have other test cases since they r hidden
import java.util.Scanner;
import java.util.*;
public class Main {
static class pair {
int first, second;
public pair(int first, int second) {
this.first = first;
this.second = second;
}
}
static int getSubarraySum(int sum[], int i, int j) {
if (i == 0)
return sum[j];
else
return (sum[j] - sum[i - 1]);
}
static int maximumSumTwoNonOverlappingSubarray(int arr[], int N,
int K) {
int l = 0, m = 0;
int a1[] = new int[N / 2];
int a2[] = new int[N / 2];
int prod = 0;
int[] sum = new int[N];
sum[0] = arr[0];
for (int i = 1; i < N; i++)
sum[i] = sum[i - 1] + arr[i];
pair resIndex = new pair(N - 2 * K, N - K);
int maxSum2Subarray =
getSubarraySum(sum, N - 2 * K, N - K - 1)
+ getSubarraySum(sum, N - K, N - 1);
pair secondSubarrayMax =
new pair(N - K, getSubarraySum(sum, N - K, N - 1));
for (int i = N - 2 * K - 1; i >= 0; i--) {
int cur = getSubarraySum(sum, i + K, i + 2 * K - 1);
if (cur >= secondSubarrayMax.second)
secondSubarrayMax = new pair(i + K, cur);
cur = getSubarraySum(sum, i, i + K - 1)
+ secondSubarrayMax.second;
if (cur >= maxSum2Subarray) {
maxSum2Subarray = cur;
resIndex = new pair(i, secondSubarrayMax.first);
}
}
for (int i = resIndex.first; i < resIndex.first + K; i++) {
a1[l] = arr[i];
l++;
}
for (int i = resIndex.second; i < resIndex.second + K; i++) {
a2[m] = arr[i];
m++;
}
for (int i = 0; i < m; i++) {
if (a1[i] != 0 || a2[i] != 0) {
prod = prod + a1[i] * a2[m - (i + 1)];
}
}
return prod;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int k = 0;
int arr[] = new int[a];
for (int i = 0; i < a; i++) {
arr[i] = sc.nextInt();
}
int l = arr.length;
int ar[] = new int[a / 2];
for (int i = 1; i <= a / 2; i++) {
ar[k] = maximumSumTwoNonOverlappingSubarray(arr, l, i);
k++;
}
Arrays.sort(ar);
System.out.println(ar[k - 1]);
}
}
Here's an O(n^2) time, O(1) space solution.
Lets write all O(n^2) multiples in a matrix. For example:
Input {1, 2, 3, -4, 5, 6}
1 2 3 -4 5 6
1 x 2 3 -4 5 6
2 x 6 -8 10 12
3 x -12 15 18
-4 x -20 -24
5 x 30
6 x
Now pick any indexes (i, j), i ≠ j, say (0, 5).
j
1 2 3 -4 5 6
i 1 x 2 3 -4 5 6
2 x 6 -8 10 12
3 x -12 15 18
-4 x -20 -24
5 x 30
6 x
Now imagine we wanted to find the best subarray where i was first, then second, then third, etc. of a valid selection. In each iteration, we would increment i and decrement j, such that we move on the diagonal: 6, 10, -12, each time adding the multiple to extend our selection.
We can do this on each of the diagonals to get the best selection starting on (i, j), where i is first, then second, then third, etc.
Now imagine we ran Kadane's algorithm on each of the diagonals from northeast to southwest (up to where the xs are where i = j). Complexity O(n^2) time. (There's Python code in one of the revisions.)
Here is the code
n=int(input())
l=[]
res=0
l=list(map(int,input().split()))
re=[]
while(True):
if(len(l)==2):
pass
break
else:
n1=l[1]
n2=l[-1]
re.append(n1*n2)
l.remove(n1)
l.remove(n2)
for i in re:
res=res+i
print(res)
#include <iostream>
#include <cassert>
using namespace std;
template<class T> inline void umax(T &a,T b){if(a<b) a = b ; }
template<class T> inline void umin(T &a,T b){if(a>b) a = b ; }
template<class T> inline T abs(T a){return a>0 ? a : -a;}
template<class T> inline T gcd(T a,T b){return __gcd(a, b);}
template<class T> inline T lcm(T a,T b){return a/gcd(a,b)*b;}
typedef long long ll;
typedef pair<int, int> ii;
const int inf = 1e9 + 143;
const ll longinf = 1e18 + 143;
inline int read()
{
int x;scanf(" %d",&x);
return x;
}
const int N = 20001;
int n;
int a[N];
void read_inp()
{
n = read();
assert(1 <= n && n <= 20000);
for(int i = 1; i <= n; i++)
{
a[i] = read();
assert(abs(a[i]) <= int(1e6));
}
}
int main()
{
#ifdef KAZAR
freopen("f.input","r",stdin);
freopen("f.output","w",stdout);
freopen("error","w",stderr);
#endif
read_inp();
ll ans = -longinf;
for(int i = 1; i <= n; i++)
{
{
int l = i - 1, r = i;
ll best = 0ll, cur = 0ll;
while(l >= 1 && r <= n)
{
ll val = (ll)a[l] * a[r];
cur += val;
umin(best, cur);
umax(ans, cur - best);
--l;
++r;
}
}
{
int l = i - 1, r = i + 1;
ll best = 0ll, cur = 0ll;
while(l >= 1 && r <= n)
{
ll val = (ll)a[l] * a[r];
cur += val;
umin(best, cur);
umax(ans, cur - best);
--l;
++r;
}
}
}
printf("%lld\n",ans);
return 0;
}
Here is the code
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int dp[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(j==i)
dp[i][j]=0;
else if(j<i)
dp[i][j]=0;
else
dp[i][j]=arr[i]*arr[j];
}
}
cout<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cout<<dp[i][j]<<" ";
cout<<endl;
}
cout<<endl;
//find max sum diagonal
long long int global_sum=0;
//get sum of diagonal increasing i
for(int i=0;i<n;i++)
{
long long int curr_sum=0;
int j=i;
int k=n-1;
while(k>=0 && j<n){
curr_sum+=dp[j][k];
k--;
j++;
}
if(curr_sum>global_sum) global_sum=curr_sum;
}
//get sum with decreasing i
for(int i=n-1;i>=0;i--){
long long int curr_sum=0;
int j=i;
int k=0;
while(k<n && j>=0){
curr_sum+=dp[j][k];
j--;
k++;
}
if(curr_sum>global_sum) global_sum=curr_sum;
}
cout<<global_sum;}
This code passes the testcase you gave and other testcases i tried myself. Its O(n^2) complexity.

Adding integers in Range not working for negative numbers

I am trying to do this exercise:
Write a program that asks the user for N and M and adds up the
integers between N and M using the formula
SUM(N to M) = SUM( 1 to M ) - SUM( 1 to N-1 )
I can get this to work for positive numbers but not negative numbers.
static int method2(int n, int m) {
int sum = 0;
int sum2 = 0;
for (int i = 1; i <= m; i++) {
sum = sum + i;
}
for (int i = 1; i <= n - 1; i++) {
sum2 = sum2 + i;
}
System.out.println("sum: " + sum + ", sum2: " + sum2);
return sum = sum - sum2;
}
e.g.
using n = -1, m = 1 returns sum = 1.
Using n = -5, m = 5 returns sum = 15.
Using n = 5, m = -5 returns sum = -10.
These should all return 0.
e.g.
Using n = -2, m = 3, returns sum = 6.
Using n = -2, m = 4, returns sum = 10.
The problem is with for (int i = 1; i <= n - 1; i++), specifically i <= n - 1 because when n-1 <= 0 this will not run. I just can't think of a way around it.
Your formula
SUM(N to M) = SUM( 1 to M ) - SUM( 1 to N-1 )
Doesn't really make sense for negative values. If you give that up you can make your program simpler. We very often start for loops at 0 or 1 but that doesn't have to be the case. You could instead start your loop at a n which might be negative:
static int method2(int n, int m) {
int sum = 0;
for (int i = n; i <= m; i++) {
sum = sum + i;
}
System.out.println("sum: " + sum);
return sum;
}
You could always check before if n < 0.
And then do another reverse loop for negative numbers.
e.g.
int sum = 0;
if(m < 0){
for(int i = 0; i >= m; i--) {
sum += i;
}
} else {
for (int i = 1; i <= m; i++) {
sum += i;
}
}
If you really have to use that formula you could use instead of:
for (int i = 1; i <= m; i++) {
the following code which changes the index either by 1 or by -1
for (int i = 1; i <= m; i+=(int)Math.signum(m-1+0.1)) {
(added 0.1 such that in case m is 1 the result is positive and not 0)
Ofc you should do the same for n.

Implement fibonacci using recursion without using java.bignumber

I am trying to implement the Fibonacci sequence without using the BigInteger Class import, hence I rewrite my own add method, and I spent two days on it, But I don't know why the answer of the first 6 numbers is correct and the rest of the answers are the reverse of the correct one(eg. n = 7, my answer: 31 the correct one: 13; n = 15, my answer = 016, correct one= 610), and when n becomes greater, the answer gets totally wrong(not even the reversed of the correct one. This happened when n >= 25).
Any advice would be appreciated!
The following is my output:
The 0th Fibonacci number is :
0
The 1th Fibonacci number is :
1
The 2th Fibonacci number is :
1
The 3th Fibonacci number is :
2
The 4th Fibonacci number is :
3
The 5th Fibonacci number is :
5
The 6th Fibonacci number is :
8
The 7th Fibonacci number is :
31
The 8th Fibonacci number is :
12
The 9th Fibonacci number is :
43
The 10th Fibonacci number is :
55
The 11th Fibonacci number is :
98
The 12th Fibonacci number is :
441
The 13th Fibonacci number is :
332
The 14th Fibonacci number is :
773
The 15th Fibonacci number is :
016
The 16th Fibonacci number is :
789
The 17th Fibonacci number is :
7951
The 18th Fibonacci number is :
4852
The 19th Fibonacci number is :
1814
The 20th Fibonacci number is :
5676
The 21th Fibonacci number is :
64901
The 22th Fibonacci number is :
11771
The 23th Fibonacci number is :
75682
The 24th Fibonacci number is :
86364
The 25th Fibonacci number is :
52047
The 26th Fibonacci number is :
393021
The 27th Fibonacci number is :
814491
The 28th Fibonacci number is :
118413
The 29th Fibonacci number is :
922905
The 30th Fibonacci number is :
040428
And the following is my code:
package com.example.helloworld;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Fibonacci_Recursive{
public static void main(String[] args) {
long start = System.nanoTime();
long time = 0L;
for(int i = 0; time <= 60L; i++)
{
Fibonacci_Recursive fr = new Fibonacci_Recursive(i);
time = ((System.nanoTime() - start) / 1000_000_000);
}
}
private Fibonacci_Recursive(int n){
System.out.println("The " + n + "th Fibonacci number is :");
if (n <= 1){
System.out.println(n);
}
else {
int[] finalResult = getF(n);
String st = "";
for (int i = 0; i < finalResult.length; i++){
st = finalResult[i] + st;
}
System.out.println(st);
}
}
private int[] getF(int n){
int[] head = new int[1];
if (n <= 1) {
head[0] = n;
return head;
}
return add(getF(n - 1), getF(n - 2));
}
private int[] add(int[] s1, int[] s2){
int carrier = 0;
ArrayList<Integer> result = new ArrayList<>();
int[] array1 = s1;
int[] array2 = s2;
array1 = reverseGeneralArray(array1);
array2 = reverseGeneralArray(array2);
int min = array2.length;
int min2 = array1.length;
if(min2 > min) {
for (int i = 0; i < min; i++) {
int x = array1[i] + array2[i];
result.add((x + carrier) % 10);
carrier = x / 10;
}
for (int j = 0; j <= min2 - min - 1; j++) {
int index = min;
result.add((array1[index] + carrier) % 10);
carrier = (array1[index] + carrier) / 10;
index++;
}
if (carrier > 0) {
result.add(carrier);
}
Collections.reverse(result);
return convertIntegers(result);
}
else if(min2 < min)
{
for(int i = 0; i < min2; i ++){
int x = array1[i] + array2[i];
result.add((x + carrier) % 10);
carrier = x / 10;
}
for(int j = 0; j <= min - min2 - 1; j++){
int index = min2;
result.add((array2[index] + carrier) % 10);
carrier = (array2[index] + carrier) / 10;
index++;
}
if (carrier > 0) {
result.add(carrier);
}
Collections.reverse(result);
return convertIntegers(result);
}else {
for (int i = 0; i < min; i++) {
int x = array1[i] + array2[i];
result.add((x + carrier) % 10);
carrier = x / 10;
}
if (carrier > 0) {
result.add(carrier);
}
Collections.reverse(result);
return convertIntegers(result);
}
}
private static int[] convertIntegers(ArrayList<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < integers.size(); i++)
{
ret[i] = integers.get(i);
}
return ret;
}
private int[] reverseGeneralArray(int[] x){
int[] newX = new int[x.length];
for(int i = 0; i < x.length; i++){
newX[i] = x[x.length - i -1];
}
return newX;
}
}
You miss building the result, you concatenate wrong (reverse) way String st from the int[] finalResult:
private Fibonacci_Recursive(int n) {
...
for (int i = 0; i < finalResult.length; i++) {
//Replaced st = finalResult[i] + st by
st = st + finalResult[i];
}
...
}
Extra: Consider, when concatenating strings in a loop, since concatenation copies the whole string, to use StringBuilder:
StringBuilder st = new StringBuilder();
for (int i = 0; i < finalResult.length; i++) {
st.append(finalResult[i]);
}
Update: Starting from 25, an error becomes evident: the carrier is not right when the sum of two digits is equal to 10 (74025 instead of 75025). The bug is at the add method,where the carrier should be calculated as:
carrier = (x + carrier) / 10;
i.e.: you have to take into account previous carrier.

Checking terms of a sequence against values in array

Why isn't this working? I am trying to check terms of the sequence a_j)=38^j +31 against values in the array. I am saying trying to get that if the specific term in the sequence is not divisible by any of these values in the array then print it.
public class SmallestPrime {
public static void main(String[] args) {
long m =0;
int [] b = {2,3,4,5,6,7,8};
for(int j=0;j<6;j++) {
m = (long) Math.pow(38,j) + 31;
if(m % b[j] !=0) {
System.out.println(m);
}
}
}
}
Your problem is that you are looping only once.
For example when j = 2 you only check if 1475 is divisible by b[2] which happens to be 4 and 1475 is not divisible by 4 thus printing your value.
You'll need to use a nested loop to achieve what you are trying to do.
Here is a bit of code to help out:
private static void smallestPrime() {
long m = 0;
int[] b = { 2, 3, 4, 5, 6, 7, 8 };
for (int j = 0; j <= 6; j++) {
m = (long) Math.pow(38, j) + 31;
boolean prime = true;
for (int i = 0; i <= 6; i++) {
if (m % b[i] == 0) {
prime = false;
break;
}
}
System.out.println(m + " : " + prime);
}
}

Categories