Find prime numbers in specific interval in specific amount of test cases.
Example is below:
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Notice the little space between the answer also.
here's my code:
#include <iostream>
#include <cmath>
void prime (int x, int y);
using namespace std;
int main()
{
int t, x[10], y[10];
cin >> t;
for (int i = 0; i < t; i++)
//for (int j = 0; j < t; j++)
cin >> x[i] >> y[i];
while (t > 0){
for (int i = 0; i < t; i++)
prime(x[i], y[i]);
t--;
}
}
void prime(int x, int y){
bool prime = true;
for (int i = x; i <= y; i++){
for (int j = 2; j <= sqrt(i); j++){
prime = true;
if (i % j == 0)
prime = false;
}
if (prime == true)
cout << i << endl;
}
cout << endl;
}
Here's the output I get when I use the same input.
1
2
3
5
7
10
3
5
1
2
3
5
7
10
What am I doing wrong?
You should move prime = true outside of the for loop. You are currently resetting it at every iteration. As far as the printing, you don't need that << endl when you print each line. You only need a space.
Since no one's pointed it out yet, if you're wondering why you're getting three sets of output instead of two...
while (t > 0){
for (int i = 0; i < t; i++)
prime(x[i], y[i]);
t--;
}
might be better phrased as
for (int i = 0; i < t; i++)
prime(x[i], y[i]);
(The outer loop is what gives you extra output.)
Related
I am beginning to learn c++, and was working through the Project Euler challenges, and #7 asks you to find all prime numbers within a given range. After online research i decided to try using Sieve of Erastothenes, however with the code i have set up, i currently get weird values such as )2, 0) when i ask for 2 primes, and (2, 4, 5, 5) when i input 5.
#include <iostream>
#include <vector>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
int main(){
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
//creates a vector to store all values, that will eventually be whittled down to primes
vector<int> primes = {2};
//adds all numbers between 2 and chosen end point to the vector
for (int i = 3; i <= end_point; i++){
primes.push_back(i);
}
for (int i = 0; i < end_point; i++){
//starts at the first value (always 2), and feeds it into the next for loop
//once the next loop is done, it moves on to the next value in the loop and feeds that in
primes[i];
//looks at values in the vector, starting with the next value in the vector
for (unsigned int j = i+1; j < primes.size(); j++){
//checks if the value at [j] is divisible by the value at [i]
//if it is, this deletes it from the vecotr
//if not, it moves on to the next value in the vector
if(primes[j] % primes[i] == 0){
primes.erase (primes.begin() + (j-1));
}
else{}
}
//prints out all of the primes in the specified range
cout << "Primes are: ";
for (unsigned int k = 0; k <= primes.size(); k++){
cout << primes[k] << ", ";
}
}
}
You shouldn't remove element from array when you traverse it. You can try it by marking.
example:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main() {
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
//creates a vector to store all values, that will eventually be whittled down to primes
vector<int> primes = { 2 };
//adds all numbers between 2 and chosen end point to the vector
for (int i = 3; i <= end_point; i++) {
primes.push_back(i);
}
for (int i = 0; i < end_point; i++) {
//starts at the first value (always 2), and feeds it into the next for loop
//once the next loop is done, it moves on to the next value in the loop and feeds that in
int val = primes[i];
// to ensure the value is not zero
if (val == 0)
continue;
//looks at values in the vector, starting with the next value in the vector
for (unsigned int j = i + 1; j < primes.size(); j++) {
//checks if the value at [j] is divisible by the value at [i]
//if it is, this deletes it from the vecotr
//if not, it moves on to the next value in the vector
if (primes[j] > 0 && primes[j] % val == 0) {
// set the value zero to element of array.
primes[j] = 0;
}
}
//prints out all of the primes in the specified range
cout << "Primes are: ";
for (unsigned int k = 0; k <= primes.size(); k++) {
if (primes[k] > 0) // output the value which greater then zero.
cout << primes[k] << ", ";
}
}
return 0;
}
You delete wrong element. This is right:
primes.erase(primes.begin() + j);
Your last loop in wrong place. Take it out of previous 'for loop'. And you go after last element. Should be:
k < primes.size();
not
k <= primes.size();
=== Now it works properly ===
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main() {
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
vector<int> primes = { 2 };
for (int i = 3; i <= end_point; i++) {
primes.push_back(i);
}
for (int i = 0; i < end_point; i++) {
for (unsigned int j = i + 1; j < primes.size(); j++) {
if (primes[j] % primes[i] == 0) {
primes.erase(primes.begin() + j);
}
else {}
}
}
cout << "Primes are: ";
for (unsigned int k = 0; k < primes.size(); k++) {
cout << primes[k] << ", ";
}
return 0;
}
you can check prime from 2 to the sqrt of that number. this will omit duplicates and extra checks.
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
vector<int> getPrimes(int start, int end){
if( start <0 || end < 0 || end < start ){
return {};
}
int max = 0;
bool isPrime = true;
vector<int> prims = {};
for( int i = start ; i <= end ; i++ ){
max = sqrt(i);
isPrime = true;
for(int j = 2 ; j <= max ; j++ ){
if( i % j == 0 ){
isPrime = false;
break;
}
}
if(isPrime){
prims.push_back(i);
}
}
return prims;
}
int main()
{
vector<int> prims = getPrimes(0,100);
for(int n : prims) {
cout << n << '\n';
}
return 0;
}
Sqrt Reason:
imagine you want to find out that 17 is a prime number or not. the simplest way is to loop from 0 to 17 to check its multiples. but it doesn't needed to do that. the sqrt of 17 is almost 4. so you check the multiples until the number 4. the next number is 5. from 5 to 17, all the multiples that their results is smaller that 17 is from 4 to 0. because 5 * 5 is 25 . even 5 * 4 is 20. so all multiples going to be repetitious.
now you can just check multiples from 2 to square root of that number to find out the number is a prime number or not
I need to Write a program that takes in a square matrix of integers and outputs the largest sub-SQUARE-matrix sum. The first line of input is an integer which indicates the dimension of the square matrix(n*n), followed by the actual matrix row-by-row.
I have a program working however, it outputs the largest sum of a rectangle and not a square which is required.
Example input:
3
1 2 3
4 5 6
-7 -8 -9
Output:
Should be 16 (2+3+5+6) however it is outputting 21 (1+2+3+4+5+6)
As you can see, it is taking the sum of the rectangle but I need it to find a square
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int n;
int mat[100][100];
cin >> n;
int sum = 0;
int maxSum = 0;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cin>>mat[i][j];
}
}
for (int k = 0; k<n; k++)
{
for (int l = 0; l<n; l++)
{
sum = sum + mat[k][l];
if (sum < 0)
{
sum = 0;
}
if (sum > maxSum)
{
maxSum = sum;
}
}
}
cout << maxSum;
return 0;
}
You were close with your loops. But you have to sum the square for each iteration if that is what you are looking for. Here I'll assume an input and go from there.
Edit: So the summing is clearer.
#include <iostream>
#include <vector>
int main()
{
//initalize(using std::cin here) You can size then load the vectors
std::vector<std::vector<int>> mat = { {1,2,3},{4,5,6},{-7,-8,-9,} };
// then do the work...
int max = std::numeric_limits<int>::min();
//assuming 'square' is 2x2, adjust 'size()-1` if not
for (size_t i = 0; i < mat.size() - 1; ++i)
for( size_t j = 0; j < mat.at(0).size() - 1; ++j)
{
int sum =
mat[i][j] +
mat[i][j+1] +
mat[i+1][j] +
mat[i+1][j+1];
if (sum > max)
max = sum;
}
std::cout << max << std::endl;
}
I am trying to write a program which checks if 3 (or more) elements of an array are the same.
I have written a code which works almost perfectly, but it gets stuck when there are 3 pairs of equal elements and I'm not sure how to fix it.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, a[10],skirt=0;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
for(int i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
cout<<skirt<<endl;
if(skirt>=3)
{
cout << "TAIP" << endl;
}
else
{
cout << "NE" << endl;
}
}
When I input
6
3 3 2 2 1 1 i
get "TAIP" but I need to get "NE".
You can use the following algorithm: first sort the array. Then iterate each adjacent pair. If they are equal, then increment counter, if not then reset counter to 1. If counter is 3, return true. If loop does not return true, then return false.
Add the following condition in the outer for loop
for(int i = 0; i < n - 2 && skirt != 3; i++)
^^^^^^^^^^^^^^^^^^^^^^^
{
skirt = 1;
^^^^^^^^^
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
Of course before the loop you should check whether n is not less than 3. For example
if ( not ( n < 3 ) )
{
for(int i = 0; i < n - 2 && skirt != 3; i++)
{
skirt = 1;
for(int j = i + 1; j < n; j++)
{
if(a[i] == a[j])
{
skirt++;
}
}
}
}
Here is a demonstrative program
#include <iostream>
using namespace std;
int main()
{
int a[] = { 6, 3, 3, 2, 2, 1, 1 };
int n = 7;
int skirt = 0;
if ( not ( n < 3 ) )
{
for(int i = 0; i < n - 2 && skirt != 3; i++)
{
skirt = 1;
for(int j = i + 1; j < n; j++)
{
if ( a[i] == a[j] )
{
skirt++;
}
}
}
}
cout << skirt << endl;
if ( skirt == 3 )
{
cout << "TAIP" << endl;
}
else
{
cout << "NE" << endl;
}
return 0;
}
Its output is
1
NE
because the array does not have 3 equal elements.
Reset skirt to 0 every time you increase i if it is less than 3, or break out the loop otherwise.
Another way to do this is using a std::map, which keeps a count of the number of times a given value occurs in your array. You would stop looking as soon as you have a number that has three occurrences.
Here's a 'minimalist' code version:
#include <iostream>
#include <map>
using std::cin; // Many folks (especially here on SO) don't like using the all-embracing
using std::cout; // ... statement, "using namespace std;". So, these 3 lines only 'use'
using std::endl; // ... what you actually need to!
int main() {
int n, a[10], skirt = 0;
std::map<int, int> gots;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n && skirt < 3; i++) {
skirt = 1;
if (gots.find(a[i]) != gots.end()) skirt = gots[a[i]] + 1;
gots.insert_or_assign(a[i], skirt);
}
cout << (skirt >= 3 ? "TAIP" : "NE") << endl;
return 0;
}
I'm not saying this is any better (or worse) than the other answers - just another way of approaching the problem, and making use of what the Standard Library has to offer. Also, with this approach, you could easily modify the code to count how many numbers occur three or more times, or any number of time.
Feel free to ask for further clarification and/or explanation.
I am working on the problem at http://orac.amt.edu.au/cgi-bin/train/problem.pl?set=simple3&problemid=416. Below is the code which I came up. Sample data executed successfully but when I submit the code I am able to execute only 71% of the test cases. Not sure where went wrong. Please guide me.
Briefly the problem is as below:
I am trying to get the max friend list from the friend linking.
1 2
2 3
3 7
1 8
1 9
Output is 1 as it has more friend list
If the friend list match with max the list all.
1 2
2 3
3 7
1 8
9 10
Output should be. 1 2 3 as they have equal number of friends.
#include <bits/stdc++.h>
using namespace std;
int main(){
freopen("listin.txt","r",stdin);
freopen("listout.txt","w",stdout);
int f=0, a= 0, b= 0, m = 1;
long size = 1001;
cin >> f;
int arr[size] = {};
int x[size] = {};
for(int i = 0; i < f; i++){
cin >> a >> b;
arr[a] += 1;
arr[b] += 1;
}
for(int j = 0; j < size; j++){
if(m < arr[j]){
m = arr[j];
}
}
for(int j = 0; j < size; j++){
if(m == arr[j]){
x[j] = j;
}
}
for(int k = 0; k < size; k++){
if(x[k] > 0)
cout << x[k] << endl;
}
return 0;
}
I have to find prime numbers for t cases. Examples of input / output below:
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Notice the space between the answers as well.
#include <iostream>
#include <cmath>
bool prime (int x, int y);
using namespace std;
int main()
{
int t, x, y;
cin >> t;
for(int i = 0; i < t; i++)
cin >> x >> y;
for(int i = 0; i < t; i++){
for (int i = x; i <= y; i++)
cout << prime(x, y) << endl;
}
return 0;
}
bool prime(int x, int y){
bool prime = true;
for (int i = x; i <= y; i++){
for (int j = 2; j <= sqrt(i); j++)
if (i % j == 0)
prime = false;
return prime;
}
}
My program outputs only 1 all the time, why is that?
You are outputting the result of prime(x, y), which is a bool. This will always be zero or one.