So when I run this code:
#include <iostream>
using namespace std;
#include <vector>
#include <string>
int main()
{
int current_number = 0;
vector<int>primes;
for(int i = 0; i < 100; i++)
{
current_number++;
for(int h= 0; h < primes.size(); h++)
{
if(current_number % primes[h] == 0)
{
continue;
}
else
{
primes.push_back(current_number);
}
}
}
for(int x =0; x < 100; x++)
{
cout << primes[x];
}
}
I get a segmentation fault. Im pretty sure it has something to do with vectorprimes. But, I'm not sure exactly what. The purpose of the code is to find every prime number between 1 and 100.
Among the problems in the posted code.
The inner loop body will never be entered because primes is initially empty the only code that changes it is in that loop.
Even after fixing the initial primes content with {2} and starting the counter loop with 3, the logic in the inner loop is still wrong. It appends on ever non-zero modulo. That shouldn't be done at all in the inner loop. Rather, the loop should break on any zero-modulo, and the outer loop then only appends to primes when it knows the inner loop didn't break early.
The final reporting loop assumes there are 100 primes in the first 100 numbers, which clearly isn't the case. Either it should be iterating based on container size, using iterators, or better still, just used ranged-for.
Minor: the current_number is pointless; just use i from the outer loop and start it at 3.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> primes = {2};
for (int i = 3; i <= 100; i++)
{
bool isprime = true;
for (auto x : primes)
{
if (i % x == 0)
{
isprime = false;
break;
}
}
if (isprime)
primes.emplace_back(i);
}
for (auto x : primes)
std::cout << x << ' ';
std::cout << '\n';
}
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Note
There are better ways to do this. I suggest you investigate how to build a Sieve of Eratosthenes or similar sieve. In truth, the above code is already over halfway there. It wouldn't take much more to do it.
Related
I want to sort using the "Bubble Sort" algorithm of the 2d array. My array size will be about array[100000][100000]. my input number will be n=100,000.
For now we can use a small size of the array to fix the sorting issue.
I need to sort them in descending order for the first number(first number's line).
If the first number of 2 values are the same, then I have to sort them according to their second number.
Finally I have to output the result into a txt file
Let's' understand using an example. Here, my input looks like this
41 11
34 4
69 4
78 6
62 8
5 5
81 3
5 10
above our input example and we have a couple of inputs. Now I need to sort them descending orders for the first number. But if the first number of 2 values are the same, then sort them according to their second number.
Example output below,
81 3
78 6
69 4
62 8
41 4
34 4
5 10
5 5
If anyone can please help me.
I am a beginner so I am trying to input the file manually to solve this sorting problem. I can solve the sorting problem then I will try to input and out the text.
Something I have tried but not worked. I am still trying to solve it.
#include<bits/stdc++.h>
#include <algorithm>
using namespace std;
int main ()
{
int arr[100][100];
int n,j;
cin >>n;
cout << "Please enter a number: " << endl;
for(int i=0;i<n;i++)
{ for (int j=i; j<n; j++)
{
cin>>arr[i][j];
}
}
cout << "Unsorted array:" << endl;
for (int i=0; i<n; i++)
{
for (int j=i; j<n; j++)
{
cout<<arr[i][j]<<"\t";
}
}
for (int i=0; i<=n; i++)
{
for (int j=i+1; j<=n-1; j++)
{
int temp;
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
return 0;
}
Use a std::vector<std::array<int,2>>for your base container. The dynamic growth capabilities of std::vector solves your stack space issue, and the std::array use gives you tied cell comparison. I.e. you can do this:
std::array<int, 2> ar1{1,2}, ar2{1,3};
if (ar1 < ar2) ...
and it will do the right thing. The result then boils down to effectively this:
#include <iostream>
#include <array>
#include <vector>
#include <utility>
int main()
{
std::vector< std::array<int,2> > v;
std::size_t n;
if (std::cin >> n && n > 0)
{
std::array<int,2> row;
while (n-- && std::cin >> row[0] && std::cin >> row[1])
v.emplace_back(row);
// bubblesort the content
std::size_t len = v.size();
while (len-- > 0)
{
bool swapped = false;
for (std::size_t i=0; i<len; ++i)
{
// std::array support multi-cell comparison.
if (v[i] < v[i+1])
{
// use library swap to swap entire row.
std::swap(v[i], v[i+1]);
swapped = true;
}
}
// early exit if no swaps happened on the last pass
if (!swapped)
break;
}
// report final output.
for (auto const& row : v)
std::cout << row[0] << ' ' << row[1] << '\n';
}
}
Input
8
41 11
34 4
69 4
78 6
62 8
5 5
81 3
5 10
Output
81 3
78 6
69 4
62 8
41 11
34 4
5 10
5 5
Can somebody tell me what is the problem with this program?
The idea is to display "Yes" if the vector array satisfies all these criteria:
The array elements are not sorted in ascending order.
The array contains distinct elements.
All the array elements should have a value between 1 to n inclusive.
Otherwise "No".
The program aborts when it reaches the line at if(bSort).
Is there anything wrong with the iterator increment?
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
std::string solve(vector <int> &a, int n) {
vector<int> visited (n);
int i=0;
for(std::vector<int>::iterator it = a.begin(); it != a.end(); ++it) {
i++;
if((it+1)!=a.end() && (*it > *(it+1)))
{
bSort = false;
}
if(std::find(visited.begin(), visited.end(), *it)!=visited.end())
{
return "No";
}
else
{
visited[i] = *it;
}
if(*it <= 0 || *it > n)
{
return "No";
}
}
if(bSort)
return "No";
else
return "Yes";
}
int main() {
int q;
cin >> q;
for(int a0 = 0; a0 < q; a0++){
int n;
cin >> n;
vector<int> a(n);
for(int a_i = 0; a_i < n; a_i++){
cin >> a[a_i];
}
std::string result = solve(a,n);
cout << result << endl;
}
return 0;
}
The issue appears to be happening only with the following input:
1
30
18 8 24 20 7 17 5 9 26 21 25 12 11 15 30 13 19 16 22 10 14 1 3 29 23 2 6 28 4 27
I'm not sure the problem has to do with iterators specifically.
At the very beginning of the loop, variable i is incremented before it's used, which means the set of numbers that i will range between is [1, vector.size()]. This means that at some point, you'll access vector[vector.size()], which is undefined behavior and can crash your program.
In your program specifically, given the input you provided, because none of the numbers in your example code are duplicated, the else branch of the std::find(...) conditional statement is always executed, which means you end up calling visited[30] at some point, which again, is out of bounds and undefined behavior, potentially causing a crash.
to be specific , in that program :
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
for (int i = -100; i <=100; i++)
{
sum += i;
}
cout << sum << endl;
return 0;
}
sum's value is 0 while in the condition that if i <=100 the compiler should add one to to the integer i but it didn't when the value became 100 although the condition is <= not only <
sorry for my bad English
you did this: -100 -99 -98 -97 ... + 97 +98 +99 +100 = 0
It does, but you have to understand that the loop condition (middle part, i<=100) is checked after the loop iteration statement (last part, i++) is executed. This is not the natural reading order.
I am trying to code a "Conways Game of Life" Visualization. I think I have a solid idea on how to go about it but my issue I am running into is this: When I attempt to output the rows and columns of my 2d array, it starts jumping between numbers towards the end and it never stops scrolling the numbers. It seems to get caught on the "x" of 78.
#include <iostream>
#include <cstring>
#include <cstdlib>
#define HEIGHT 25
#define WIDTH 80
using namespace std;
void makeBoard();
int seed = 0;
int main()
{
makeBoard();
}
void makeBoard()
{
int board[79][24] = {0};
/* Seed the random number generator with the specified seed */
srand(seed);
for(int x = 0; x <= 79; x++)
{
for(int y = 0; y <= 24; y++)
{
/* 50% chance for a cell to be alive */
if(rand() % 100 < 50)
{
board[x][y] = {1};
}
else
{
board[x][y] = {0};
}
/*if(board[x][y] == 1) {
cout << "SPAM" << endl;
}*/
//this is just printing out the current location it is iterating through.
cout << "X: " << x << " Y: " << y << endl;
}
cout << endl;
}
}
all of the code needed to run it should be right there.
Thank you for your help and patience.
Your indices are out of bounds. an array of [79][24] has indices going from 0-19, and 0-23. Your condition stop at 79 and 24 respectively. Replace <= with <.
An array of size N goes from 0 to n-1. You need to replace the <= with <, since you're running out of bounds along each dimension of the array.
Note also that you only have 79 columns and 24 rows, not the 80 and 25 you defined at the top of your program. You can fix this by doing:
int board[HEIGHT][WIDTH];
Then substitute the 79 and 24 with HEIGHT and WIDTH respectively, and change the <= in the loop conditions to <. That way all you need do is change those single values at the top to change the size of the board throughout.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Which is the fastest algorithm to find prime numbers?
is there any way to make this more optimize..
#include <vector>
int main()
{
std::vector<int> primes;
primes.push_back(2);
for(int i=3; i < 100; i++)
{
bool prime=true;
for(int j=0;j<primes.size() && primes[j]*primes[j] <= i;j++)
{
if(i % primes[j] == 0)
{
prime=false;
break;
}
}
if(prime)
{
primes.push_back(i);
cout << i << " ";
}
}
return 0;
}
int main(int argc, char *argv[]) {
cout << "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 ";
}
:-)
More seriously, you could avoid repeatedly squaring the primes by caching primes[j] * primes[j] and save on multiplications.
Sieve of Eratosthenes is a great algorithm for generating prime numbers up to a certain number (which is not what your title states, but what your code implies).
Yes, change i++ to i+=2 and it will work twice as fast.
do not do primes[j]*primes[j] <= i just check primes[j] <= 7
use i+=2
Yes. As Marion has suggested, you can use the Sieve of Eratosthenes but you should be aware of the details. The code you have written looks superficially like the sieve, but it isn't. It's called trial division and it has a different algorithmic complexity than the sieve.
The sieve performs a pass which takes Theta(n/p) time for each prime p. This results in a total complexity of O(n log log n). IIRC the proof is a bit complicated and involves the prime number theorem.
Your algorithm performs pi(sqrt(p)) divisions for each prime number p and a smaller number of divisions for non-primes. (where pi is the prime-counting function). Unfortunately I can't come up with the total complexity off the top of my head.
In short, you should change the code to use an array and mark all the non-primes.
This article addresses the same topic in functional programming languages.
Yes, Sieve of Eratosthenes is the best option (If you need most than 100 numbers this is the best implementation). This is my implementation:
#include <vector>
#include <iostream>
#include <cmath>
using namespace std;
vector<int> sieve(int n){
vector<bool> prime(n+1,true);
vector<int> res;
prime[0]=prime[1]=false;
int m = (int)sqrt(n);
for(int i=2; i<=m; i++){
if(prime[i])
for(int k=i*i; k<=n; k+=i)
prime[k]=false;
}
for(int i=0; i<n ;i++)
if(prime[i])
res.push_back(i);
return res;
}
int main(){
vector<int> primes = sieve(100);
for(int i=0; i<primes.size() ;i++){
if(i) cout<<", ";
if(primes[i]) cout<<i;
}
cout<<endl;
}