loop for adding prime numbers in c++ - c++

here is a loop that is supposed to add prime numbers only and ignore non prime numbers but it is not working properly ,my skills are pretty basic , so please try to simplify your answers as much as possible,
#include <iostream>
using namespace std;
int main()
{
int n = 0, a = 0, sum = 0;
cin >> n;
for (int j = 1; j <= n; j++)
{
cin >> a;
if (a == 1)
{
continue;
}
if (a == 2 || a == 3)
{
sum += a;
}
if (a % 2 == 0)
{
continue;
}
for (int i = 3; i < a; i++)
{
if (a % i != 0)
{
sum += a;
}
else
{
continue;
}
}
}
cout << sum;
return 0;
}

I would prefer using this function instead. You should add cmath library:
bool isPrime(int number) {
if (number <= 1)
return false;
for (int i = 2; i <= sqrt(number); i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
But if you want to continue with your code, after checking a == 2 || a == 3 you should continue. And last part before for loop you should define some boolean like bool isPrime = true. Then if its finds a divider you should assing it to false and break.
Your full code should be something like this:
#include <iostream>
using namespace std;
int main()
{
int n = 0, a = 0, sum = 0;
cin >> n;
for (int j = 1; j <= n; j++)
{
cin >> a;
if (a == 1)
{
continue;
}
if (a == 2 || a == 3)
{
sum += a;
continue;
}
if (a % 2 == 0)
{
continue;
}
bool isPrime = true;
for (int i = 3; i < a; i++)
{
if (a % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime) {
sum += a;
}
}
cout << sum;
return 0;
}

Related

print all the prime numbers upto an upperlimit

#include<iostream>
using namespace std;
int main(){
int n=5;
int i = 2;
for (i; i <= n; i++)
// for all num to n
{
int j = 2;
bool divide = false;
for (j; j <= n - 1; j++)
// for checking each num
{
if (i % j == 0)
{
divide = true;
break;
}
}
if (divide == false)
{
cout << i << " ";
}
}
return 0;
}
my Q is that
//please tell me why it is not working
//it is expected to give ans 2,3,5 which it is not giving why???
maybe I found the issue.
I think that the problem here is:
for (j; j <= n - 1; j++)
Here you did j<=n-1;
So to fix this just do:
for(j; j < i; j++){
//this should fix
So everything should look like this:
#include<iostream>
using namespace std;
int main() {
int n = 5;
int i = 2;
//check prime numbers starting from i and max n using for loop
for (i = 2; i <= n; i++) {
bool divide = false;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
divide = true;
break;
}
}
if (!divide) {
//!divide is equal to divide=false
cout << i << " ";
}
}
}

How to compare elements in an array for equality?

I've come across this problem where I have to transform a number from the decimal system to the binary and compare if the numbers are equal
Example:
7 is becoming 111
The output is false
and where 5 is 101
The output is true
I've figured out how to transform the numbers with an array
But have no idea how to compare them
#include<iostream>
using namespace std;
int main()
{
int num;
cin >> num;
int arr[8] = {};
if ((num >= 0) && (num <= 255))
{
while (num != 0)
{
for (int i = 0; i < 8; i++)
{
if (num % 2 == 0)
arr[i] = 0;
else
{
arr[i] = 1;
}
num = num / 2;
}
}
for (int i = 7; i >= 0; i--)
cout << arr[i];
cout << endl;
}
else
{
cout << "error" << endl;
return 1;
}
system("pause");
return 0;
}

Replacing nested for loops in C++

So I wrote this code but the problem is I have a restriction in my assignment that I can't use nested for loops in my code.
#include<iostream>
using namespace std;
void Exchange(int* a, int* b) {
int var;
var = *a; //For swapping or exchanging values. O_o
*a = *b;
*b = var;
}
void Algorithm(int array[], int nerd) {
int i, j, k; //This is the actual algorithm which is required. ;)
for (i = 0; i < nerd;) {
for (j = i + 1; j < nerd; j++) {
if (array[j] < array[j - 1])
Exchange(&array[j], &array[j - 1]);
}
nerd--;
for (k = nerd - 1; k > i; k--) {
if (array[k] < array[k - 1])
Exchange(&array[k], &array[k - 1]);
}
i++;
}
}
int main() {
int n, i;
cout << "\nEnter the count of numbers for the algorithm: ";
cin >> n;
int arr[10];
for (i = 0; i < n; i++) {
cout << "Enter number " << i + 1 << ": ";
cin >> arr[i];
}
Algorithm(arr, n);
cout << "\nFinal Data you entered (after the algorithm performed)";
for (i = 0; i < n; i++)
cout << " -> " << arr[i];
return 0;
}
One loop using modulus on the one loop counter:
#include <utility> // std::swap
void Algorithm(int array[], int nerd) {
int max = nerd * (nerd - 1);
for(int i = 1; i < max; ++i) {
// If at start of the removed inner loop, skip i % nerd == 0
if(i % nerd == 0) ++i;
if (array[i % nerd] < array[(i-1) % nerd])
std::swap(array[i % nerd], array[(i - 1) % nerd]);
}
}
Demo
Without modulus, decreasing nerd and restarting with i = 1 each time i == nerd:
void Algorithm(int array[], int nerd) {
for(int i = 1; nerd > 1; ++i) {
if(i == nerd) { // start of the removed inner loop
--nerd; // the highest number will already be in place
i = 1;
}
if (array[i] < array[i - 1])
std::swap(array[i], array[i - 1]);
}
std::cout << "ted " << nerd << '\n';
}
Demo
An alternative to quit looping early if no swaps were made last round:
void Algorithm(int array[], int nerd) {
if(nerd < 2) return;
bool done = true;
for(int i = 1;; ++i) {
if(i % nerd == 0) {
if(done) break;
++i;
done = true;
}
if (array[i % nerd] < array[(i-1) % nerd]) {
std::swap(array[i % nerd], array[(i-1) % nerd]);
done = false;
}
}
}
Demo
The alternative without modulus and with the decreasing nerd optimization:
void Algorithm(int array[], int nerd) {
if(nerd < 2) return;
bool done = true;
for(int i = 1;; ++i) {
if(i == nerd) {
if(done || --nerd == 1) break;
i = 1;
done = true;
}
if (array[i] < array[i - 1]) {
std::swap(array[i], array[i - 1]);
done = false;
}
}
}
Demo

How many primes in between a given range? C++ [duplicate]

This question already has answers here:
Printing prime numbers from 1 through 100
(22 answers)
Closed 9 years ago.
So, I made this little program. It gives all the correct outputs, but when uploading it to the online judge it throw me away a Time Limited Exceeded. Any ideas on how to make it more efficient?
Here is my code.
int const MAX = 1000001;
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int main()
{
int count = 0, array[MAX], a, b, pi = 0;
bool end = false;
for(int i = 1; i <= MAX; i++)
{
count = 0;
for(int j = 2; j <= sqrt(i); j++)
{
if(i % j == 0)
{
array[i]=0;
count++;
break;
}
}
if(count == 0 && i != 1){
array[i]=1;
}
}
do {
cin >> a >> b;
pi = 0;
if ((a == 0) && (b == 0)) {
end = true;
break;
}
else {
for (int i = a; i <= b; i++) {
if (array[i] == 1) {
pi ++;
}
}
cout << pi << endl;
}
} while (end == false);
cout << endl;
return 0;
}
You may consider using Sieve of Eratosthenes. It is an efficient prime generation algorithm.

Why is my simple recursive method's final return value always off by 1?

I'm attempting to create a text-based version of this game.
Code:
#include <iostream>
#include <vector>
#include <ctime>
class Clickomania {
public:
Clickomania();
std::vector<std::vector<int> > board;
int move(int, int);
bool isSolved();
void print();
void pushDown();
bool isValid();
};
Clickomania::Clickomania()
: board(12, std::vector<int>(8,0)) {
srand((unsigned)time(0));
for(int i = 0; i < 12; i++) {
for(int j = 0; j < 8; j++) {
int color = (rand() % 3) + 1;
board[i][j] = color;
}
}
}
void Clickomania::pushDown() {
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 12; j++) {
if (board[j][i] == 0) {
for(int k = j; k > 0; k--) {
board[k][i] = board[k-1][i];
}
board[0][i] = 0;
}
}
}
}
int Clickomania::move(int row, int col) {
bool match = false;
int totalMatches = 0;
if (row > 12 || row < 0 || col > 8 || col < 0) {
return 0;
}
int currentColor = board[row][col];
board[row][col] = 0;
if ((row + 1) < 12) {
if (board[row+1][col] == currentColor)
{
match = true;
totalMatches++;
totalMatches += move(row+1, col);
}
}
if ((row - 1) >= 0) {
if (board[row-1][col] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row-1, col);
}
}
if ((col + 1) < 8) {
if (board[row][col+1] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row, col+1);
}
}
if ((col - 1) >= 0) {
if (board[row][col-1] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row, col-1);
}
}
return totalMatches;
}
void Clickomania::print() {
for(int i = 0; i < 12; i++) {
for(int j = 0; j < 8; j++) {
std::cout << board[i][j];
}
std::cout << "\n";
}
}
int main() {
Clickomania game;
game.print();
int row;
int col;
std::cout << "Enter row: ";
std::cin >> row;
std::cout << "Enter col: ";
std::cin >> col;
int numDestroyed = game.move(row,col);
game.print();
std::cout << "Destroyed: " << numDestroyed << "\n";
}
The method that is giving me trouble is my "move" method. This method, given a pair of coordinates, should delete all the squares at that coordinate with the same number and likewise with all the squares with the same number connected to it.
If you play the link I gave above you'll see how the deletion works on a click.
int Clickomania::move(int row, int col) {
bool match = false;
int totalMatches = 0;
if (row > 12 || row < 0 || col > 8 || col < 0) {
return 0;
}
int currentColor = board[row][col];
board[row][col] = 0;
if ((row + 1) < 12) {
if (board[row+1][col] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row+1, col);
}
}
if ((row - 1) >= 0) {
if (board[row-1][col] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row-1, col);
}
}
if ((col + 1) < 8) {
if (board[row][col+1] == currentColor)
{
match = true;
totalMatches++;
totalMatches += move(row, col+1);
}
}
if ((col - 1) >= 0) {
if (board[row][col-1] == currentColor) {
match = true;
totalMatches++;
totalMatches += move(row, col-1);
}
}
return totalMatches;
}
My move() method above works fine, as in it will delete the appropriate "blocks" and replace them with zeros, however the number of destroyed (value returned) is always one off (too small). I believe this is because the first call of move() isn't being counted, but I don't know how to differentiate between the first call or subsequent calls in that recursive method.
How can I modify my move() method so it returns the correct number of destroyed blocks?
It looks like you're incrementing totalMoves in the wrong place(s). You should count the match at the point where you set board[r][c] = 0 and remove the other references to totalMoves++.
You are right that the first call isn't being counted, it's only counting the recursive calls.
0 based indexing. You dont want to check > you want >=
you wanna check row >= 12 col >= 8