Wil - 1 year ago 71
C++ Question

# Difficulty implementing limit to how many integers print on each line C++

I have seen this question around, but I am having difficulty implementing some of the solutions into my own code.

The program being worked on finds all the prime numbers in an array and times how long it takes to find all the prime numbers. One of the stipulations though is making the program print only 10 numbers per line. I have tried a couple different methods to get this to work, but none of them print how I need them to. Here is the current code:

``````#include "stdafx.h"
#include <iostream>
#include <time.h>
#include <stdio.h>
using namespace std;

static const int N = 1000;

int main()
{

int i, a[N];

clock_t start = clock();

for (i = 2; i < N; i++) a[i] = i;
for (i = 2; i < N; i++)
if (a[i])
for (int j = i; j*i < N; j++) a[i*j] = 0;

start = clock() - start;

for (i = 2; i < N; i++)
if (a[i]) cout << " " << i;
if ((i = 1) % 10 == 0)
cout << "\n";

printf("\nIt took %d clicks (%f seconds) to find all prime numbers.\n", start, ((float)start) / CLOCKS_PER_SEC);

return 0;
}
``````

I'm sure this is a simple mistake on my own part, or maybe I dont have the proper understanding on how this works. If anyone can shed some light on the subject it would be greatly appreciated, thank you.

Just create a new counter, to count the number of primes found.

``````int primes = 0;
for (i = 2; i < N; i++) {
if (a[i]) {
primes++;
cout << " " << i;
if ( primes % 10 == 0)
cout << "\n";
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download