How can I find the prime numbers in a one-dimensional array in C++ in a simple way ??
{
int list[5];
int i,sum = 0;
for (i = 0; i < 5; i++)
{
cout << "Enter The List [" << i << "]: "; cin >> list[i];
sum = sum + list[i];
}
cout << endl;
cout << "The Sum Is:" << sum << endl;
}
Emphasizing on the comment of #john:
Create a function (say bool is_prime(int n)).
Now check if the number n is a prime or not.
So, you need to check if each of the positive integers more than 1 before n divides n or not without leaving any remainder. There's a shorter workaround, which will greatly reduce the computational cost. Just checking till the square root of the number n will do. Hence the function sqrt() is used.
So now, our is_prime() function is pretty easy to build as you can see:
bool is_prime(int n)
{
int i,p=0;
for(i=2;i<=sqrt(n);i++)
{
if(n%i==0)
{
p=1;
break; //even if one integer divides the number, then it is composite.
}
}
if(p==1)
return false; //The number is a composite.
else
return true; //The number is a prime.
}
Now, you just need to pass every value of the array into this function, and your job will be done.
Also, this program can be made even better if you check for the special case of 1 which is neither composite nor prime. A suggestion is, check your array element if it is 1 or not. If not, then pass the value in the function, else just print that it is a 1.
NOTE: The sqrt() function is available in the cmath library in C++ so you need to include that in your program too.
You can use sieve of Eratosthenes. Simply how it works is it iterates (from 2) through an boolean array and if arr[i] is prime (is true, i is the given number), sets every multiplicity to false.
Start with an array filled with true
Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
is prime 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
first you have to set arr[0] and arr[1] to false, because these are not prime numbers
Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
is prime 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Now, you go to 2 and set every multiplication of it to false.
in this case 4, 6, 8, 10, 12, 14 16...
Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
is prime 0 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0
Then do it for 3
so 6, 9, 12, 15
Numbers 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
is prime 0 0 1 1 0 1 0 1 0 0 0 1 0 1 0 0 0
4 is not prime so you skip it
5 is prime so you do the same as for 2 and 3 (10 -> false, 15 -> false etc.)
after you use it, you can simply check if n is prime
if (arr[n] == true)
cout << n << " is prime";
else
cout << n << " is not prime";
you can find it easily on internet, for example here (there are some optimizations you can add, too)
Related
I've often heard that you should never mod the result of your random number generator if you want a uniform distribution. However, I've seen that using a std::uniform_int_distribution makes no difference for significantly small ranges.
Below is an example using both mod and uniform_int_distribution for values 0 - 15:
std::mt19937 gen;
gen.seed(0);
int ROWS = 6;
int COLS = 10;
std::cout << "mod: \n";
for (size_t i = 0; i < ROWS; ++i){
for (size_t j = 0; j < COLS; ++j){
std::cout << std::setw(2) << gen() % 16 << " ";
}
std::cout << "\n";
}
std::cout << "\n";
gen.seed(0);
std::uniform_int_distribution<> distrib(0, 15);
std::cout << "dist: \n";
for (size_t i = 0; i < ROWS; ++i){
for (size_t j = 0; j < COLS; ++j){
std::cout << std::setw(2) << distrib(gen) << " ";
}
std::cout << "\n";
}
results:
mod:
12 15 5 0 3 11 3 7 9 3
5 2 4 7 6 8 8 12 10 1
6 7 7 14 8 1 5 9 13 8
9 4 3 0 3 5 14 15 15 0
2 3 8 1 3 13 3 3 14 7
0 1 9 9 15 0 15 10 4 7
dist:
12 15 5 0 3 11 3 7 9 3
5 2 4 7 6 8 8 12 10 1
6 7 7 14 8 1 5 9 13 8
9 4 3 0 3 5 14 15 15 0
2 3 8 1 3 13 3 3 14 7
0 1 9 9 15 0 15 10 4 7
I guess it has something to do with 2 bytes? I'm just wondering how this is valid mathematically since its stepping through the random number generator and modding results. Does this mean mod creates a uniform distribution if the range is small enough? And why a 2 byte range and not more?
Using the modulo operator will frequently introduce a bias into the returned results when the number of unique values returned by your source of random bits is not a multiple of the divisor.
As a simple example, if your random source returns 4 bits (0-15) and you want values in the range 0-2, using gen() % N you'll get 6 0s, 5 1s, and 5 2s. This biases your results to the low side.
Using multiply-then-divide (gen() * N / RANGE) can still leave an imbalance in the specific number of each result returned, but the imbalance will be spread out evenly among the results which reduces or eliminates the low bias. It also has to contend with overflow in the multiplication. With the previous example, you'll get 5 0s, 6 1s, and 5 0s.
A third alternative would be to check the returned bits to see if the value is among the highest result (that would result in the bias) and regenerate the random bits if this is the case. This introduces a conditional in the code and the time to generate a random number is open ended (rather than fixed).
I have been stuck on a problem having two recursive functions in it. I could not understand the mechanism of loop and stack behind it. This are the lines of code of my program.
#include<iostream>
using namespace std;
int test(int num)
{
if (num != 0)
{
num = num - 1;
test(num);
cout << num << " ";
test(num);
}
}
int main()
{
test(3);
}
This is the output of the program
0 1 0 2 0 1 0
Can someone explain me the output of this program using stack?
Unroll the recursion. The output in the rightmost column below matches what you are getting.
executed printed
-------- -------
test(3)
test(2)
test(1)
test(0)
cout << 0 0
test(0)
cout << 1 1
test(1)
test(0)
cout << 0 0
test(0)
cout << 2 2
test(2)
test(1)
test(0)
cout << 0 0
test(0)
cout << 1 1
test(1)
test(0)
cout << 0 0
test(0)
For brevity lets call this function f.
What does this function do? Well, it prints something if its argument is positive and calls itself recursively twice, with the argument decreased by 1. If the argument is zero, the function immediately returns, so the recursion starting from positive arguments will be stopped there. For negative arguments we have an error.
Now, What does it do? It decreases its argument, then calls itself on it, prints it, calls itself again. We can draw a diagram like this:
n: [f(n-1) n-1 f(n-1)]
which means that (neglecting the problem of the number of spaces) it prints whatever f(n-1) prints, then n-1 (and a space), then again f(n-1). The first conclusion: the printout will be symmetric about its central element. And it actually is. If you expand this formula a step further, you'll get this:
n-1: [f(n-2) n-2 f(n-2) n-1 f(n-2) n-2 f(n-2)]
So, in the central position there will always be n-1. Its left-hand and right-hand "neighbour substrings" will be identical. n-2 will be seen in this sequence twice. It's not difficult to see that n-3 will be seen 4 times, etc., till 0 will be seen 2^n times. One can even see that 0 will occupy every second position.
How many numbers will we see? 1 + 2 + ... + 2^n = 2^{n-1} -1. For n=2 this gives 2^3 - 1 = 8 - 1 = 7. That's correct.
What may be the "meaning" of this sequence?
Look (n = 5):
0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0
Now, take the consequtive integers
1 2 3 4 5 6 7 8 9 10 ... 31
and count the number of times each of them is divisible by 2. Can you see? 1 is not divisible by 2, hence 0 in your sequence. 2 is divisible once, hence 1. 3 is not divisible by 2 - hence 0. 4 is divisible twice, hence 2 on the fourth position. Etc., etc.
You have n coins with certain values. Your task is to find all the money sums you can create using these coins.
Input
The first input line has an integer n: the number of coins.
The next line has n integers x1,x2,…,xn: the values of the coins.
Output
First print an integer k: the number of distinct money sums. After this, print all possible sums in increasing order.
Constraints
1≤n≤100
1≤xi≤1000
Example
Input:
4
4 2 5 2
Output:
9
2 4 5 6 7 8 9 11 13
I have written a code which works perfectly for the small inputs but gives the wrong answer to the large inputs. Please help to find the mistake and how do I correct it.
my code is:
#include <bits/stdc++.h>
using namespace std;
set<long long> s;
// Prints sums of all subsets of array
void subsetSums(long long arr[], long long n)
{
// There are totoal 2^n subsets
long long total = 1 << n;
// Consider all numbers from 0 to 2^n - 1
for (long long i = 0; i < total; i++)
{
long long sum = 0;
// Consider binary reprsentation of
// current i to decide which elements
// to pick.
for (long long j = 0; j < n; j++)
if (i & (1 << j))
sum += arr[j];
// Print sum of picked elements.
if (sum)
s.insert(sum);
}
}
// Driver code
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n;
cin >> n;
long long arr[n];
for (long long i = 0; i < n; i++)
{
cin >> arr[i];
}
subsetSums(arr, n);
cout << s.size() << "\n";
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << " ";
return 0;
}
for example, it gives the wrong answer for
50
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
as
18
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36
the correct output should be:
50
1 2 3 4 ... 50
your code is simply too slow 2^n subsets gives 1,267,650,600,228,229,401,496,703,205,376 subsets in the worst case (when n=100) while C++ does on average about 1000,000,000 operations per second.
This problem can be solved with dynamic programming, consider having an array dp of size 100001, so that dp[x] denotes if sum of x is possible to achieve.
Base case is easy - sum of 0 is possible without using any coins: dp[0]=1
Then for each coin we can try to increase existing sums by coins value to fill up our table:
for each coinValue:
for coinSum = 100000 - coinValue; coinSum >=0; coinSum--)
if(dp[coinSum])
dp[coinSum + coinValue]=1
Notice that we are looping backwards, this is done on purpose so that each coin gets used only once.
Complexity: O(n^2*maxCoinValue)
Your algorithm is poor, but the reason you're getting wrong results is because you're overflowing int. long long total = 1<<n; shifts an int left by n places, and the fact you're assigning the result to a long long is irrelevant.
You can find problems like this using ubsan. Here's a reproduction of your problem, including warning messages from ubsan:
$ clang++ -fsanitize=undefined a.cpp -o a && ./a
50
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
a.cpp:11:25: runtime error: shift exponent 50 is too large for 32-bit type 'int'
a.cpp:22:24: runtime error: shift exponent 32 is too large for 32-bit type 'int'
18
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36
I need to read integers from a text file into a two-dimensional array.
-1 indicates the end of array. Every array supposes to have 6 positive integers (-1 does NOT count as part of the array).
For example, if my text file contains the following integers:
1 3 4 6 1 7 -1 1 3 5 7 2 3 -1 2 5 7 2 6 3 -1
That means when these integers are read into the program, there will be 3 arrays:
1st Array: 1 3 4 6 1 7
2nd Array: 1 3 5 7 2 3
3rd Array: 2 5 7 2 6 3
I wrote a program to assess if each array has a correct length (6 integers) AND correct integers (all integers should be positive) and output corresponding error messages if these criteria are not met.
#include <iostream>
#include <fstream>
#include <string>
#define MAX_ROWS 3
#define MAX_COLUMNS 2
using namespace std;
int main()
{
string fileName = "testdata.txt"; //declare a string to store the Input File's name
ifstream inFile; //name the input file connection
inFile.open(fileName); //open the Input File
string errorMessage = "Input file cannot be found"; //Declare a string to store an error message, just in case the Input file doesn't exist or cannot be found
if (!inFile) { //If the Input File doesn't not exist, then display the error message
cout << errorMessage << '\n'; //also store the error message to the Output file
system("pause");
return 0; //end the program if the Input File does not exist
}
int checkNbr;
int ArrB[MAX_ROWS][MAX_COLUMNS];
int size = MAX_ROWS * MAX_COLUMNS;
bool bad = false;
bool invalidnum = false;
while (!inFile.eof())
{
for (int i = 0; i < MAX_ROWS;i++) {
for (int j = 0; j < MAX_COLUMNS; j++) {
inFile >> ArrB[i][j];
if (ArrB[i][j] == -1) {
bad = true;
cout << "\nThe array does not have enough integers" << endl;
break;
//return 1;
}
else {
if (ArrB[i][j] < 1) {
invalidnum = true;
}
}
cout << *(*(ArrB + i) + j) << " ";
}
}
if (invalidnum == true) {
invalidnum = false;
cout << "\nThere is/are negative number(s) or zero(s) in the array imported from your text file.\n";
}
if (bad == false) {
inFile >> checkNbr;
if (checkNbr == -1) {
cout << "\nThe size of the array is correct." << endl;
}
else {
while (checkNbr != -1)
{
cout << checkNbr;
cout << " ";
inFile >> checkNbr;
}
cout << "\nYou have too many numbers in this array\n";
}
}
}
return 0;
}
If I run my program:
Case 1 - PASSED
1 2 3 4 5 6 -1 3 5 2 1 6 8 3 2 5 -1 3 3 5 6 7 5 -1
Case 2 – PASSED
1 2 3 4 5 -6 -1 3 -5 2 1 6 8 -1 3 5 6 7 5 -1
Case 3 – FAILED(!)
1 2 3 4 -1 1 2 3 4 5 6 7 8 -1 1 2 3 4 5 -1
As you can see, case 3 failed. The second array (1 2 3 4 5 6 7 8) is actually longer than the declared array size, but it’s printing out “The array does not have enough integers” error message…..
The ONLY time this program won't work is when the first array does not have enough integers.
Any comments or hints would be appreciated!
The problem
bad is not reset after processing it.
Solution
Move bool bad = false; into the while (!inFile.eof()) loop body so it gets reset every iteration. If you define variables with the narrowest possible scope you can usually avoid this problem, so you should strongly consider doing the same thing with the rest of your variables.
This will solve the bug that was asked about and at least one other bug you haven't found yet. This leaves at least two more outstanding bugs for you to resolve, and both have been covered in the question's comments.
TL;DR version
A quick walk through of input 1 2 3 4 -1 1 2 3 4 5 6 7 8 -1 1 2 3 4 5 -1
1 2 3 4 -1 is parsed and found to be bad, so bad is set to true and the testing for a too-long value and clean-up is skipped. The file hasn't ended, so the program loops and starts reading the next array.
input remaining:
1 2 3 4 5 6 7 8 -1 1 2 3 4 5 -1
output so far:
1 2 3 4
The array does not have enough integers
1 2 3 4 5 6 is parsed. This fills the array and the for loops exit. bad is still true, so the check for overflow is skipped and no message is printed.
Input remaining:
7 8 -1 1 2 3 4 5 -1
output so far:
1 2 3 4
The array does not have enough integers
1 2 3 4 5 6
Now 7 8 -1 is parsed. This is too short to be an array and reported. Take careful note of what this does to the output.
Input remaining:
1 2 3 4 5 -1
output so far:
1 2 3 4
The array does not have enough integers
1 2 3 4 5 6 7 8
The array does not have enough integers
Whoops. Looks like 1 2 3 4 5 6 7 8, not merely 7 8, was too short.
the program then parses 1 2 3 4 5 and finds it to be too short.
Input remaining:
output so far:
1 2 3 4
The array does not have enough integers
1 2 3 4 5 6 7 8
The array does not have enough integers
1 2 3 4 5
The array does not have enough integers
Problem
I need to compute a function of an array of integers. For every three-element subset (or triplet) of the array, I need to compute the term floor((sum of triplet)/(product of triplet)). Then I need to return the sum of all such terms.
Example
Input (length; array):
5
1 2 1 7 3
Output:
6
Explanation
The following triplets exist in the given array:
1 2 1
1 2 7
1 2 3
1 1 7
1 1 3
1 7 3
2 1 7
2 1 3
2 7 3
1 7 3
Considering these triplets from the sample input:
1 2 1 contributes 2, because floor((1+2+1)/(1*2*1)) = floor(4/2) = 2
1 2 3 contributes 1
1 1 7 contributes 1
1 1 3 contributes 1
2 1 3 contributes 1
All other triplets contribute 0 to the sum.
Hence the answer is (2+1+1+1+1)=6.
My Solution
What I tried is complexity O(n^3). Code is given below:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long t,n[300005],sum=0,mul=1,i,j,k,res=0;
cin >> t;
for(i=0;i<t;i++)
cin >>n[i];
for(i=0;i<t-2;i++)
for(j=i+1;j<t-1;j++)
for(k=j+1;k<t;k++)
{
sum = n[i]+n[j]+n[k];
mul = n[i]*n[j]*n[k];
res += floor(sum/mul);
}
cout << res << endl;
return 0;
}
Is there any hint of better optimization?
While still O(n^3), you could save some operations by caching the redundant calculations between n[i] and n[j] as you iterate over n[k].
For example:
long sum_ij,mul_ij;
for(i=0;i<t-2;i++) {
for(j=i+1;j<t-1;j++) {
sum_ij = n[i]+n[j];
mul_ij = n[i]*n[j];
for(k=j+1;k<t;k++)
{
sum = sum_ij+n[k];
mul = mul_ij*n[k];
res += floor(sum/mul);
}
}
}