I am trying to implement the Sieve of Eratosthenes algorithm but it giving a runtime error.
didn't get any output though. after providing the input,
#include<iostream>
using namespace std;
//Sieve Approach - Generate an array containing prime Numbers
void prime_sieve(int *p) {
//first mark all odd number's prime
for (int i = 3; i <= 10000; i += 2) {
p[i] = 1;
}
// Sieve
for (long long int i = 3; i <= 10000; i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= 10000; j = j + i ) {
p[j] = 0;
}
}
}
//special case
p[2] = 1;
p[1] = p[0] = 0;
}
int main() {
int n;
cin >> n;
int p[10000] = {0};
prime_sieve(p);
//lets print primes upto range n
for (int i = 0; i <= n; i++) {
if (p[i] == 1) {
cout << i << " ";
}
}
return 0;
}
compiler didn't throwing any error also it is not providing the output also
program freezes for some seconds and then terminates
As mentioned in the comments, you are going out of bound.
There is also some confusion about the meaning of p[].
In addition, you are not using the value of n in the function, which leads to unnecessary calculations.
Here is a tested programme (up to n = 10000):
#include <iostream>
#include <vector>
#include <cmath>
//Sieve Approach - Generate an array containing prime Numbers less than n
void prime_sieve(std::vector<int> &p, long long int n) {
//first mark all odd number's prime
for (long long int i = 4; i <= n; i += 2) {
p[i] = 0;
}
// Sieve
for (long long int i = 3; i <= sqrt(n); i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= n; j = j + i ) {
p[j] = 0;
}
}
}
//special cases
p[1] = p[0] = 0;
}
int main() {
long long int n;
std::cout << "Enter n: ";
std::cin >> n;
std::vector<int> p (n+1, 1);
prime_sieve(p, n);
//lets print primes upto range n
for (long long int i = 0; i <= n; i++) {
if (p[i] == 1) {
std::cout << i << " ";
}
}
return 0;
}
Given m integer from 1 to m, for each 1 <=i <= m find the smallest prime x that i % x = 0 and the biggest number y which is a power of x such that i % y = 0
My main approach is :
I use Eratos agorithm to find x for every single m like this :
I use set for more convenient track
#include<bits/stdc++.h>
using namespace std;
set<int> s;
void Eratos() {
while(!s.empty()) {
int prime = *s.begin();
s.erase(prime);
X[prime] = prime;
for(int j = prime * 2; j <= L ; j++) {
if(s.count(j)) {
int P = j / prime;
if( P % prime == 0) Y[j] = Y[P]*prime;
else Y[j] = prime;
}
}
}
signed main() {
for(int i = 2; i<= m; i++) s.insert(i);
Eratos();
for(int i = 1; i <= m; i++) cout << X[m] << " " << Y[m] ;
}
with X[m] is the number x corresponding to m and same as Y[m]
But it seems not really quick and optimal solution. And the memory request for this is so big and when m is 1000000. I get MLE. So is there an function that can help to solve this problem please. Thank you so much.
Instead of simply marking a number prime/not-prime in the original Sieve of Eratosthenes, save the corresponding smallest prime factor which divides that number.
Once that's done, the biggest power of the smallest prime of a number would mean to simply check how many times that smallest prime appears in the prime factorization of that number which is what the nested for loop does in the following code:
#include <iostream>
#include <vector>
using namespace std;
void SoE(vector<int>& sieve)
{
for (int i = 2; i < sieve.size(); i += 2)
sieve[i] = 2;
for (int i = 3; i < sieve.size(); i += 2)
if (sieve[i] == 0)
for (int j = i; j < sieve.size(); j += i)
if(sieve[j] == 0)
sieve[j] = i;
}
int main()
{
int m;
cin >> m;
vector<int> sieve(m + 1, 0);
SoE(sieve);
for (int i = 2; i < sieve.size(); ++i)
{
int x, y;
x = y = sieve[i];
for (int j = i; sieve[j / x] == x; j /= x)
y *= x;
cout << x << ' ' << y << endl;
}
}
I didn't get what you're trying to do but I understand that you're trying to use Sieve of Eratosthenes to find prime numbers. Well, what you probably need is a bitset, it's like a boolean array but uses bits instead of bytes which means it uses less memory. Here's what I did:
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
vector<int> primes;
int main()
{
const int m = 1e7;
bitset<m> bs;
int limit = (int) sqrt (m);
for (int i = 2; i < limit; i++) {
if (!bs[i]) {
for (int j = i * i; j < m; j += i)
bs[j] = 1;
}
}
for (int i = 2; i < m; i++) {
if (!bs[i]) {
primes.push_back (i);
}
}
return 0;
}
I made a similar post on here but didn't get any feedback. The problem came from here.
I am trying to simply print out the entries of the longest increasing matrix. I thought I had it figure out when I tried the following matrix:
2 2 1
1 2 1
2 2 1
I got an output of:
1
2
Then when I increased n , m = 4. I got this matrix:
2 2 1 1
2 1 2 2
1 2 2 3
1 2 1 3
And this output for the paths entries:
1
1
2
When it should be just:
1
2
3
Here is my code:
#include <algorithm>
#include <cmath>
#include <list>
#include <vector>
#include <stdio.h>
#include <random>
#include <utility>
#include <iostream>
void printPath(std::vector<int> &numPaths) {
std::sort(numPaths.begin(), numPaths.end());
for(int i = 0; i < numPaths.size(); i++) {
std::cout << numPaths[i] << std::endl;
}
}
int DFS(int i, int j, const std::vector<std::vector<int> > &matrix, std::vector<std::vector<int> > &length) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
std::vector<int> path;
if(length[i][j] == -1) {
int len = 0;
for(auto p: dics) {
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue; // Check to make sure index is not out of boundary
if(matrix[x][y] > matrix[i][j]) { // compare number
len = std::max(len, DFS(x,y,matrix,length));
}
}
length[i][j] = len + 1;
}
return length[i][j];
}
int longestPath(std::vector<std::vector<int> > matrix) {
int n = matrix[0].size();
if (n == 0) {
return 0;
}
int m = matrix.size();
if (m == 0) {
return 0;
}
std::vector<std::vector<int> > length(m, std::vector<int>(n,-1));
std::vector<int> numPaths;
int len = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int newLen = DFS(i,j,matrix,length);
if(newLen > len) {
numPaths.push_back(matrix[i][j]);
}
len = std::max(len, DFS(i, j, matrix, length));
}
}
printPath(numPaths);
return len;
}
int main() {
// Specify the number of rows and columns of the matrix
int n = 4;
int m = 4;
// Declare random number generator
std::mt19937 gen(10);
std::uniform_int_distribution<> dis(1, 3);
// Fill matrix
std::vector<std::vector<int> > matrix;
for(int i = 0; i < m; i++) {
std::vector<int> row;
for(int j = 0; j < n; j++) {
row.push_back(0);
}
matrix.push_back(row);
}
// Apply random number generator to create matrix
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
matrix[i][j] = dis(gen);
}
}
// Print matrix to see contents
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
//std::vector<std::vector<int> > mat = {{1,2,3}};
int result = longestPath(matrix);
std::cout << "The longest path is " << result << std::endl;
}
I would really appreciate if someone can tell me where I am going wrong.
#include <algorithm>
#include <cmath>
#include <vector>
#include <stdio.h>
#include <random>
#include <utility>
#include <iostream>
#define MATRIX_SIZE 1000
void printPath(std::vector<int> &numPaths) {
std::sort(numPaths.begin(), numPaths.end());
for(int i = 0; i < numPaths.size(); i++) {
std::cout << numPaths[i] << std::endl;
}
}
int DFS(int i, int j, const std::vector<std::vector<int> > &matrix, std::vector<std::vector<int> > &length) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
std::vector<int> path;
if(length[i][j] == -1) {
int len = 0;
for(auto p: dics) {
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue; // Check to make sure index is not out of boundary
if(matrix[x][y] > matrix[i][j]) { // compare number
len = std::max(len, DFS(x,y,matrix,length));
}
}
length[i][j] = len + 1;
}
return length[i][j];
}
void printMatrix(std::vector<std::vector<int>> &matrix) {
for (int i =0; i < matrix.size(); i++) {
for (int j =0; j < matrix[0].size(); j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
std::vector<int> generatePath(int i, int j, const std::vector<std::vector<int>> &matrix, const std::vector<std::vector<int>> &length) {
int max_length = length[i][j];
std::vector<int> path(max_length, 0);
for (int current_length = max_length; current_length >= 1; current_length--) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
int index = max_length - current_length;
for (auto p: dics) {
path[index] = matrix[i][j];
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue;
if (current_length - length[x][y] == 1) {
i = x;
j = y;
break;
}
}
}
printPath(path);
return path;
}
int longestPath(std::vector<std::vector<int> > matrix) {
int n = matrix[0].size();
if (n == 0) {
return 0;
}
int m = matrix.size();
if (m == 0) {
return 0;
}
std::vector<std::vector<int> > length(m, std::vector<int>(n,-1));
std::vector<int> numPaths;
int len = 0;
int maxRow = 0;
int maxCol = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int currentLength = DFS(i, j, matrix, length);
if (currentLength > len) {
len = currentLength;
maxRow = i;
maxCol = j;
}
}
}
generatePath(maxRow, maxCol, matrix,length);
return len;
}
int main(int argc, char *argv[]) {
std::mt19937 gen(10);
std::uniform_int_distribution<> dis(1, 1000000);
// Fill matrix
std::vector<std::vector<int> > matrix;
for(int i = 0; i < MATRIX_SIZE; i++) {
std::vector<int> row;
for(int j = 0; j < MATRIX_SIZE; j++) {
row.push_back(0);
}
matrix.push_back(row);
}
// Apply random number generator to create matrix
for(int i = 0; i < MATRIX_SIZE; i++) {
for(int j = 0; j < MATRIX_SIZE; j++) {
matrix[i][j] = dis(gen);
}
}
// Print matrix
//printMatrix(matrix);
timespec start, end;
clock_gettime(CLOCK_REALTIME, &start);
printf("the longest path is %d\n", longestPath(matrix));
clock_gettime(CLOCK_REALTIME, &end);
printf("found in %ld micros\n", (end.tv_sec * 1000000 + end.tv_nsec / 1000) - (start.tv_sec * 1000000 + start.tv_nsec / 1000));
return 0;
}
# Print the Longest Increasing Path in a Matrix #
class Solution:
# Possible directions allowed from the given question.
DIRECTIONS = [[1, 0], [-1, 0], [0, 1], [0, -1]]
def longestIncreasingPath(self, matrix):
# From the given question:
# ----- m = rows ----- i
# ----- n = cols ----- j
m = len(matrix)
if m == 0:
return 0
n = len(matrix[0])
if n == 0:
return 0
cache = [[0] * n for _ in range(m)]
longestPath = 0
maximum = 1
for i in range(m):
for j in range(n):
longestPath = self.depthFirstSearch(matrix, i, j, m, n, cache)
maximum = max(maximum, longestPath)
return (cache, maximum)
def depthFirstSearch(self, matrix, i, j, m, n, cache):
if cache[i][j] != 0:
return cache[i][j]
maxPath = 1
for direction in self.DIRECTIONS:
x = direction[0] + i
y = direction[1] + j
if x < 0 or y < 0 or x >= m or y >= n or matrix[x][y] <= matrix[i][j]:
continue
length = 1 + self.depthFirstSearch(matrix, x, y, m, n, cache)
maxPath = max(maxPath, length)
cache[i][j] = maxPath # Save the value at i, j for future usage.
return maxPath
def printPath(self, matrix):
# Check if longestPath is 0.
if not self.longestIncreasingPath(matrix):
return None
length = self.longestIncreasingPath(matrix)[1]
cache = self.longestIncreasingPath(matrix)[0]
# From the given question:
# ----- m = rows ----- i
# ----- n = cols ----- j
m = len(cache)
n = len(cache[0])
location = []
# Traverse the cache to obtain the location of the starting point of the longest increasing path in the matrix.
# Time complexity, T(n) = O(n*m) ----- if not a square matrix.
for i in range(m):
for j in range(n):
if cache[i][j] == length:
location.extend([i, j])
i, j = location[0], location[1]
result = [matrix[i][j]] # The result container is initialised with the element of the matrix at the obtained position
# Time complexity, T(n) = O(4n) ----- where n = length of longest increasing path in the given matrix and the 4 being the length of the DIRECTIONS matrix.
for _ in range(length):
for direction in self.DIRECTIONS:
x = direction[0] + i
y = direction[1] + j
if x < 0 or y < 0 or x >= m or y >= n or cache[i][j] - 1 != cache[x][y]:
continue
result.append(matrix[x][y])
i = x
j = y
return result
I found this problem somewhere in a contest and haven't been able to come up with a solution yet.
The boy has apples and keeps in boxes. In one box no more than N/2.
How many methods he can put candies to boxes.
So what I'm trying to do is to implement solution using DP. Here is my code:
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include <vector>
#define size 1002
using namespace std;
long long a[size][size];
int n, k;
int main()
{
cin >> n >> k;
int kk = n/2;
for(int i = 0; i <= k; ++i)
a[0][i] = 1;
a[0][0] = 0;
for(int i = 0; i <= kk; ++i)
a[i][1] = 1;
for(int i = 1; i <= n; ++i) {
for(int j = 2; j <= k; ++j) {
int index = 0;
long long res = 0;
while(1) {
res += a[i-index][j - 1];
index += 1;
if(index == kk + 1 || i-index < 0)
break;
}
a[i][j] = res;
}
}
cout << a[n][k] << endl;
}
But the problem is that we have large numbers in input like:
2 ≤ N ≤ 1000 is a quantity of the candies, N - even; 2 ≤ S ≤ 1000 - is a quantity of small boxes.
So, for input like N = 1000 and S = 1000, I have to spent 5*10^8 operations. And the numbers are very big, so I have to use BigInteger arithmetics?
Maybe there is algorithm to implement the problem in linear time? Thanks and sorry for my English!
You can easily decrease the time complexity from O(kn^2) into O(nk) by the following observation:
for(int i = 1; i <= n; ++i) {
for(int j = 2; j <= k; ++j) {
int index = 0;
long long res = 0;
while(1) {
res += a[i-index][j - 1];
index += 1;
if(index == kk + 1 || i-index < 0)
break;
}
a[i][j] = res;
}
}
for each a[i][j], we can easily see that
a[i][j] = sum a[k][j - 1] with k from (i - n/2) to i
So, if we create an array sum to store the sum from all indexes of the previous step, we can reduce one for loop from the above nested loop
a[i][j] = sum[i] - sum[i - (n/2) - 1];
Pseudo code:
long long sum[n + 1];
for(int j = 2; j <= k; ++j) {
long long nxt[n + 1];
for(int i = 1; i <= n; ++i) {
int index = 0;
long long res = sum[i] - sum[i - (n/2) - 1];
a[i][j] = res;
nxt[i] = nxt[i - 1] + a[i][j];//Prepare the sum array for next step
}
sum = nxt;
}
Note: This above code is not handled the initialization step for array sum, as well as not handle the case when i < n/2. Those cases should be obvious to handle.
Update:
My below Java solution get accepted by using similar idea:
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int s = in.nextInt();
BigInteger[][] dp = new BigInteger[n + 1][2];
BigInteger[][] count = new BigInteger[2][n + 1];
int cur = 1;
for (int i = 0; i <= n / 2; i++) {
dp[i][0] = BigInteger.ONE;
count[0][i] = (i > 0 ? count[0][i - 1] : BigInteger.ZERO)
.add(dp[i][0]);
}
for (int i = n / 2 + 1; i <= n; i++) {
dp[i][0] = BigInteger.ZERO;
count[0][i] = count[0][i - 1];
}
for (int i = 2; i <= s; i++) {
for (int j = 0; j <= n; j++) {
dp[j][cur] = dp[j][1 - cur].add((j > 0 ? count[1 - cur][j - 1]
: BigInteger.ZERO)
.subtract(j > n / 2 ? count[1 - cur][j - (n / 2) - 1]
: BigInteger.ZERO));
count[cur][j] = (j > 0 ? count[cur][j - 1] : BigInteger.ZERO)
.add(dp[j][cur]);
}
cur = 1 - cur;
}
out.println(dp[n][1 - cur]);
out.close();
}
My homework will create a program that check the numbers in an array with a given pattern. Program must take the matrix dimensions and terms in the matrix as arguments from command line. For example program name is myProg.exe and we want to check a 2x3 dimensioned matrix with (maximum dimension limit is 20x20):
1 2 3
4 5 6
Then I will run your program as.
The program will check a special matrix pattern and prints out ACCEPTABLE or NOT MATCH according to the values we put from the console. The Special Pattern: In a row major representation the cells of the matrix must obey this rule. Some terms of the matrix must be sum or product of the neighbor cells. In row major representation the sum and product operations are placed as given in the examples. Sum and Product cells follows each other with one free cells. For Odd rows the sequence starts with free cells and in Even Rows the sequence starts with Sum or Product cell.
My code is here:
#include <iostream>
#include <sstream>
using namespace std;
static int iter = 0;
static unsigned int sat=3, sut=2;
bool ok = false;
int *accepted;
int *array;
string isAcceptable(int mat[]) {
int l, co = 0;
bool operation = false;
int mat2[sat][sut];
for (int i = 0; i < sat; i++) {
for (int j = 0; j < sut; j++) {
mat2[i][j] = mat[co];
co++;
}
}
for (int i = 0; i < sat; i++) {
if (i % 2 == 0)
l = 1;
else
l = 0;
for (int j = l; j < sut; j += 2) {
int totalProduct;
if (!operation) {
totalProduct = 0;
if (j > 0)
totalProduct += mat2[i][j - 1];
if (j < sut - 1)
totalProduct += mat2[i][j + 1];
if (i > 0)
totalProduct += mat2[i - 1][j];
if (i < sat - 1)
totalProduct += mat2[i + 1][j];
} else {
totalProduct = 1;
if (j > 0)
totalProduct *= mat2[i][j - 1];
if (j < sut - 1)
totalProduct *= mat2[i][j + 1];
if (i > 0)
totalProduct *= mat2[i - 1][j];
if (i < sat - 1)
totalProduct *= mat2[i + 1][j];
}
if (mat2[i][j] != totalProduct)
return "NOT MATCH";
operation = !operation;
}
}
return "ACCEPTABLE";
}
void change(int index1, int index2) {
int temp;
temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
iter++;
}
void combine(int mat[], int len) {
if(ok)
return;
array = new int[len];
*array = *mat;
if (len <= sat * sut) {
for (int i = len; i < sat * sut - 1; i++) {
for (int j = i; j < sat * sut; j++) {
combine(array, len + 1);
change(i, j);
if (isAcceptable(array) == ("ACCEPTABLE")) {
int accepted[sat*sut];
*accepted = *array;
ok = true;
return;
}
}
}
} else
return;
}
string isAcceptableCombine(int mat[]) {
combine(mat, 6);
if (ok)
{
cout<< " TRUE Sequense";
return "ACCEPTABLE";
}
else
cout<< " FALSE Sequense";
return "NOT MATCH";
}
int main(int argc, char** argv) {
int matris[] = {1,2,1,4,1,6};
isAcceptableCombine(matris);
}
My code's result is always returning TRUE Sequence.
Where is my mistake?