diff --git a/C/0-1_knapsack.c b/C/0-1_knapsack.c new file mode 100644 index 0000000..41ad1f7 --- /dev/null +++ b/C/0-1_knapsack.c @@ -0,0 +1,74 @@ +#include + +int max(int a,int b) // function to find the maximum value +{ + if(b>a) + return b; + return a; +} + +int main() +{ + printf("Enter the size of array:\n"); + int n; + scanf("%d",&n); + + int w[n+1]; //weight array + printf("Enter the weights of elements\n"); + for(int i = 1; i <= n; i++) + { + scanf("%d",&w[i]); + } + int val[n+1]; // value array + printf("Enter the value of elements\n"); + for(int i = 1; i <= n; i++) + { + scanf("%d",&val[i]); + } + + int weight; // weight of knapsack + printf("Enter the weight of knapsack\n"); + scanf("%d",&weight); + + int dp[n+1][weight+1]; + for(int i=0;i<=n;i++) + { + for(int j=0;j<=weight;j++) + { + if(i==0||j==0) + dp[i][j]=0; // initializing dp array + } + } + + for(int i=1;i<=n;i++) + { + for(int j=1;j<=weight;j++) + { + if(j>=w[i]) + dp[i][j]=max(val[i]+dp[i-1][j-w[i]],dp[i-1][j]); + else + dp[i][j]=dp[i-1][j]; + } + } + printf("%d",dp[n][weight]); // printing max value + + return 0; +} +/* + Input: size of array, weight of elements, value of elements, weight of knapsack + + Output: Maximum value of knapsack + + time complexity: O(n*wg), + where n is number of elements and wg is weight of knapsack + + + Sample input: + 4 + [3, 2, 4, 1] + [100, 20, 60, 40] + 5 + + Output: 140 + +*/ \ No newline at end of file diff --git a/C/README.md b/C/README.md index 9fe8bfa..8e527ff 100644 --- a/C/README.md +++ b/C/README.md @@ -28,3 +28,5 @@ Format: -[Program name](name of the file) [Tree Traversals](Tree_traversals.c) [Fibonacci_series](fibonacci_series_code.c) + +[0/1 Knapsack](0-1_knapsack.c) diff --git a/CPP/README.md b/CPP/README.md index 43ed59a..25f518e 100644 --- a/CPP/README.md +++ b/CPP/README.md @@ -72,3 +72,5 @@ Format: -[Program name](name of the file) [N-Queens Proplem](N-QueensProblem.cpp) [Topological Sorting](Topological_sorting.cpp) + +[sieve of eratosthenes](sieve_of_eratosthenes.cpp) diff --git a/CPP/sieve_of_eratosthenes.cpp b/CPP/sieve_of_eratosthenes.cpp new file mode 100644 index 0000000..5fb9b79 --- /dev/null +++ b/CPP/sieve_of_eratosthenes.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +int main() +{ + cout << "Enter the number:" << endl; + int n; + cin >> n; + // marking prime number as zero and non-prime as 1. + + int a[n+1] = {0}; // initially assuming all numbers to be prime + a[0] = 1, a[1] = 1; + + vector primes; + + for(long long i = 2; i <= n; i++) + { + if(a[i] == 0) + { + for(long long j =i * i; j <= n;j += i) // iterating over all the multiples. + a[j] = 1; // marking non-prime number as 1 + } + } + + for(int i = 1; i <= n; i++) + { + if(a[i] == 0) + primes.push_back(i); //pushing all the primes in the primes vector. + } + + for(int i=0;i