Counting prime numbers in C++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I count all the "prime" numbers instead of displaying them?
Example:
cout << "there are 125 prime numbers";
I'm using the number 1000 because I want to find out how many prime numbers it has.
I don't want to display the found prime numbers but I want to know how many have been found.
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main()
{
for (int a=2 ; a < 1000 ; a++)
{
bool prime = true;
for(int c=2 ; c*c <= a ; c++)
{
if(a % c == 0)
{
prime = false;
break;
}
}
if(prime) cout << a << " ";
}
return 0;
}

Reformatting your code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <fstream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main() {
for (int a = 2; a < 1000; a++) {
bool prime = true;
for (int c = 2; c*c <= a; c++) {
if(a % c == 0) {
prime = false;
break;
}
}
if(prime) cout << a << " ";
}
return 0;
}
Instead of printing it out each time through the loop, you need to make a variable to count each time the number is prime. Start by adding a variable outside of your outer for loop:
int main() {
int num_primes = 0;
for (int a = 2; a < 1000; a++) {
Next, instead of printing whenever a number is prime, just increment the counter:
if(prime) {
num_primes += 1;
}
Finally, just before you return from main(), print out the number of primes:
cout << num_primes << endl;
return 0;
While this definitely looks like your homework, I hope you learn something from this.

Try this,
#include < iostream>
#include < iomanip>
#include < string>
#include < sstream>
#include < fstream>
#include < math.h>
#include < stdio.h>
using namespace std;
int main()
{
int count=0;
for (int a=2 ; a < 1000 ; a++)
{
bool prime = true;
for (int c=2 ; c*c <= a ; c++)
{
if(a % c == 0)
{
prime = false;
break;
}
}
if(prime) count++;
}
cout <<"No of prime numbers : "<< count;
return 0;
}

Easy, just increment a counter instead of printing the value. You can also obtain a fairly decent approximation of Euler's totient function using the equation N/(log(N)-1)...

Related

Program not working for some reason, could someone pls help me fix it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Could someone please help me fix my program and explain why it s not working?
It's supposed to generate n points with 2 coordinates, which are both random numbers. The values themselves are random but have to scale the interval from 0 to some chosen value k. All the points have to be apart from each other by some radius which is taken to be 1.
For some reason my program doesn't even start. When I run it, Windows just says that the program is not responding and is trying to diagnose the problem.
Please simplify your explanation as much as possible since I'm a complete beginner and probably won't understand otherwise. Thanks a bunch in advance.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
int n=5;
int k=100;
vector<vector<double>> a(n, vector<double> (2));
srand(132);
//a[0][1]=k*((float(rand()))/RAND_MAX);
//a[0][0]=k*((float(rand()))/RAND_MAX);
for(int i=0; i<n;){
a[i][0]=k*((float(rand()))/RAND_MAX);
a[i][1]=k*((float(rand()))/RAND_MAX);
for (int j=0; j<n; j+=1){
if (sqrt(pow((a[i][1]-a[j][1]),2)+pow((a[i][0]-a[j][0]),2))<=1){
i=i;
break;}
else if(j==n-1){
cout << a[i][0] << " " << a[i][1] << endl;
i+=1;}
}}
return 0;
}
Your code lacks structure. That's why it is hard to understand, as you now learned even for you.
I think a good start would be to write a class for point and two functions, one for random points and for point distance then all, especially the double loops, will become much easier to read and debug.
Look at this:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct Point
{
Point() = default;
float x;
float y;
};
float scaled_random(int k)
{
return k*((float(rand()))/RAND_MAX);
}
float distance(const Point& a, const Point& b)
{
return sqrt(pow(a.y-b.y,2)+pow(a.x-b.x,2));
}
int main()
{
int n = 5;
int k = 100;
vector<Point> a(n);
srand(132);
for (int i=0; i<n; ) {
a[i].x = scaled_random(k);
a[i].y = scaled_random(k);
for (int j=0; j<n; j+=1) {
if (distance(a[i], a[j]) <= 1) {
i = i;
break;
} else if (j == n-1) {
cout << a[i].x << " " << a[i].y << endl;
i += 1;
}
}
}
return 0;
}
The issue is still the same, but it has now more structure, better formatting and superfluous includes removed.
Maybe you can see the problem yourself much better this way.
The first time through your code i and j will both be zero, this means a[i][1] - a[j][1] and a[i][0] - a[j][0] are zero, this resets i to 0, breaks the loop and starts again resulting in an infinite loop.
Checking i != j fixes the problem:
if (i != j && sqrt(pow((a[i][1] - a[j][1]), 2) + pow((a[i][0] - a[j][0]), 2)) <= 1) {
Your code might be better structured as:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <algorithm>
int main()
{
int n = 5;
int k = 100;
std::vector<std::vector<double>> a(n, std::vector<double>(2));
srand(132);
for (int i = 0; i < n; i++) {
auto end = a.begin() + i;
do
{
a[i][0] = k * ((float(rand())) / RAND_MAX);
a[i][1] = k * ((float(rand())) / RAND_MAX);
}
while (end != std::find_if(a.begin(), end, [&](const std::vector<double>& element)
{
return sqrt(pow((a[i][1] - element[1]), 2) + pow((a[i][0] - element[0]), 2)) <= 1;
}));
std::cout << a[i][0] << " " << a[i][1] << "\n";
}
return 0;
}
Using this code only the values before i are checked each time rather than all of the values.
rand should be avoided in modern c++, see Why is the use of rand() considered bad?
As the elements of your vector always have 2 elements it'd be better to use std::pair or std::array.
pow may be quite an inefficient way to square two numbers. The sqrt could be avoided by squaring your distance instead.
Using the above points your code could become:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <array>
#include <random>
using point = std::array<double, 2>;
double distanceSquared(const point& a, const point& b)
{
auto d0 = a[0] - b[0];
auto d1 = a[1] - b[1];
return d0 * d0 + d1 * d1;
}
int main()
{
int n = 5;
int k = 100;
std::vector<point> a(n);
std::random_device rd;
std::mt19937_64 engine(rd());
std::uniform_real_distribution<double> dist(0, k);
for (int i = 0; i < n; i++) {
auto end = a.begin() + i;
do
{
a[i][0] = dist(engine);
a[i][1] = dist(engine);
}
while (end != std::find_if(a.begin(), end, [&](const point& element)
{
return distanceSquared(a[i], element) <= 1;
}));
std::cout << a[i][0] << " " << a[i][1] << "\n";
}
return 0;
}

Incorrect 'for' loop results C++

I am a beginner at using C++ so I was wondering if someone would be able to help me out as I'm currently trying to print a 'for' loop. The 'alfa' loop is printing correctly but when that information is called upon by the 'sina' loop, only zeros are being printed in the console.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <new>
#include <ctime>
#include <string>
#include <sstream>
#include <vector>
const double convToRad = pi/180.0;
int main(){
int INDEX = 91;
double alfa[INDEX] {0};
double sina[INDEX] {0};
for (int p = 90; p >= 0; p--){
alfa[INDEX] = p*convToRad;
//std::cout << alfa[INDEX] << std::endl;
}
for (int e = 0; e <= 90; e++){
sina[INDEX] = sin(alfa[INDEX]);
std::cout << sina[INDEX] << std::endl; //only prints 0's
}
return 0;
}
Your are accessing wrong memory location.
INDEX=91;
You had typed INDEX instead of p and e in both the loops.
So accessing a single wrong location which may gives a junk value or crash the program.
A few notes:
Don't use magical numbers, use constants.
Don't use the numbers in the array which are constant as you did.
Try a simple fix:
for (int p = 0; p < INDEX; p++) {
// storing 90* stuff in first index, 89* in second and so on...
alfa[p] = (90 - p) * convToRad;
// std::cout << alfa[p] << std::endl;
}
for (int e = 0; e < INDEX; e++) {
sina[e] = sin(alfa[e]);
std::cout << sina[e] << std::endl;
}

Stroustrup Chapter4 Exercise 11

I am working through Programming: Principles and Practice Using C++ and I am on chapter 4, exercise 11. The question wants you to write a program that detects all primes between 1 ans 100. This is what I have so far
//This program finds the prime numbers between 1 and 100
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
vector<int>primes;
bool ptest(int y)
{
int p=0, x=0;
for (x==0; x<primes.size(); ++p)
{
if (y%primes[x]==0)
{
return false;
}
return true;
}
}
int main()
{
int i=3;
primes.push_back(2);
vector<int>comp;
for (i==3; i<=100; ++i)
{
if (ptest(i)==true)
{
primes.push_back(i);
}
}
for (int x:primes)
{
cout << x << " ";
}
}
For some reason, the program prints 2, followed by all of the odds from 3-100. I am not sure what I am missing here.
EDIT: Question has been answered. Thep was from a previous try that I forgot to change. The major mistake here was me not knowing that the return true value belonged outside of the loop.
Thanks
Errors:
Your return true; is in wrong position. It should be after the loop.
x have to be updated in the iterations.
Warnings:
The first expression x==0 in for loop is meaningless.
p is meaningless because its value is not used.
Try this:
bool ptest(int y)
{
for (int x=0; x<primes.size(); ++x)
{
if (y%primes[x]==0)
{
return false;
}
}
return true;
}

C++ integer digits to line by line

I am working with my project that will convert the integer value to each line.
Example:
23487
Output will be
2
3
4
8
7
I know the code if I will used string, but I think its better if I use integer.
My current code using string:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str("23487");
for (int i = 0; i < str.size(); i++){
cout << str[i] << endl;
}
system("pause");
return 0;
}
Can anyone help me if I use int instead of string?
For integer values larger than 0, you can use this:
void Print(int val)
{
if (val > 0)
{
Print(val/10);
cout << val%10 << endl;
}
}
Try this... This code will print as exactly you want... :)
#include <iostream>
#include <string>
using namespace std;
int main() {
int a=23487,ara[10],i=0,j;
while(a)
{
ara[i++]=a%10;
a/=10;
}
for(j=i-1;j>=0;j--)
cout<<ara[j]<<endl;
return 0;
}
Try
#include <stdio.h>
int main(int argc, char * argv[])
{
int value = 23487;
while(value > 0)
{
int d = value % 10;
value /= 10;
printf("d = %d\n", d);
}
return 0;
}
Note that the digits will be printed backwards.

Segmentation fault in c++ code unable to find reason

I am getting segmentation for the last test case (Don't know what it is ) while solving the problem GREATESC.
Concept of the problem is basic bfs. Given an undirected graph |V| <= 3500 and |E| <= 1000000
Find the minimum distance between two given vertices.
Here's the problem link http://opc.iarcs.org.in/index.php/problems/GREATESC
Here's my solution link
http://ideone.com/GqTc6k
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <cassert>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#define Pi 3.14159
#define vi vector<int>
#define pi pair<int,int>
#define si stack<int>
typedef long long int ll;
using namespace std;
bool b[3501][3501]={0};
int main ()
{
int n,m;
cin >>n>>m;
int u,v;
for (int i =1;i<= m;i++)
{
scanf("%d",&u);
scanf("%d",&v);
b[u][v]=b[v][u]=1;
}
// input completed.
int dist[n+1];
int h,V;
cin >>h>>V;
dist[h]=0;
//cout<<"hero "<<h<<" "<<V<<endl;
queue<int> q;
bool bfs[3501];
for (int i=1;i<= n;i++)bfs[i]=1;
q.push(h);
bfs[h]=0;
while (!q.empty())
{
int top = q.front();
// cout<<top<<endl;
q.pop();
for (int i = 1 ;i <= 3500;i++)
{
if(bfs[i] && b[i][top])
{
int x = i;
dist[i] = dist[top] +1;
if(x == V){cout<<dist[x]<<endl;return 0;}
bfs[x]=0;
q.push(x);
}
}
}
cout<<0<<endl;
}
You have this:
cin >>n>>m;
...
int dist[n+1];
Hence the array dist may have size less than 3500. But:
for (int i = 1 ;i <= 3500;i++)
...
dist[i] = dist[top] +1;
This code might be indexing outside of dist.
You seem to need in general to be more careful that when indexing into an array, you're inside the bounds of the array.
Consider using std::vector instead of arrays, then indexing with at to get bounds checking. Or alternatively, manually assert that values are within range:
#include <assert.h>
...
for (int i = 1 ;i <= 3500;i++)
...
assert(i >= 0 && i <= n && top >= 0 && top <= n);
dist[i] = dist[top] +1;