I have finished my program, and it runs perfectly fine, but i have one last question to ask.
I need to count how many times the number 5 appears in my vector - disqualify.
My code is below, and any help on how to determine how many times 5 appears as a disqualifying prime is greatly appreciated.
I can only get the contents of the entire vector to appear so im at a loss.
Thank you!
#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
const int MAX(100); // Number of primes to be identified
long primes[MAX] = { 2, 3, 5 }; // Initialize with first three primes
long trial(5); // Hold a candidate prime
int count(3); // Count primes found - reflects initial values
bool found(false); // Indicates when a prime is found
vector <long> nonPrimes; //Vector to hold non prime numbers
vector <long> disqualify; //Vector to hold prime numbers that disqualify the non prime numbers as prime numbers.
vector<long>::iterator fives;//Vector iterator which will be used to find how many times the number 5 disqualifies a nonPrime number.
do
{
trial += 2; // Produce next candidate value
found = false; // Reset indicator - assume it is not prime
for (int i = 0; i < count; i++) // Try division by existing primes
{
found = (trial % primes[i]) == 0; // True if no remainder
if (found) // No remainder means number is not a prime
{
nonPrimes.push_back(trial); // push_back trial values to vector nonPrimes
disqualify.push_back(primes[i]); //push back disqualifying prime numbers to disqualify vector
break; // Terminate the division loop
}
}
// The above loop will exit either due to a break or after trying all
// existing primes as a divisor. found was initialized to false. If
// found is false after exiting the loop, a divisor was not found.
if (!found) // We have a new prime: found = true! -- add numbers to vectors
primes[count++] = trial; // Save candidate in next array position
} while (count < MAX);
// Main loop has completed - we have found MAX prime numbers.
// Display the prime numbers, presenting five numbers on one line.
cout << "Prime numbers found during the program execution:" << endl;
for (int i = 0; i < MAX; i++)
{
if (i % 5 == 0) // For a new line on first line of output
cout << endl; // and on every fifth line that follows
cout << setw(10) << primes[i]; // Provide space between numbers
}
cout << endl; // All primes displayed - for a new line
/*
Display Non-primes and their disqualifiers
*/
cout << "Non-Primes identified: " << count << endl; // Identify how many nonprimes appear and display the value.
for (int i = 0; i < MAX; i++) //For loop to clarify position of output
{
if (i % 5 == 0) // For a new line on first line of output
cout << endl; // and on every fifth line that follows
cout << setw(10) << nonPrimes[i] << ":" << disqualify[i] << setw(10); // outputs nonPrime numbers and their disqualifying primes
}
cout << endl;
//Use iterator (fives) to produce how many times the digit 5 appears as a disqualifying prime number
for (fives = disqualify.begin(); fives < disqualify.end(); fives++) // bounds checking for how many times 5 appears.
{
cout << "Numer of times 5 was a disqualifier: " << *fives << endl; // output number of times 5 appears as a disqualifying prime
}
system("Pause");
return 0;
}
If I understand the question correctly, the last few lines are almost right.
//Use iterator (fives) to produce how many times the digit 5 appears as a disqualifying prime number
for (fives = disqualify.begin(); fives < disqualify.end(); fives++) // bounds checking for how many times 5 appears.
{
cout << "Numer of times 5 was a disqualifier: " << *fives << endl; // output number of times 5 appears as a disqualifying prime
}
This loop says to run one-by-one through the elements of disqualify and print "Number of times 5 was a disqualifier: " followed by the element at that point in disqualify.
You can simply change that loop to count the fives by incrementing a counter every time it hits a 5, then put the print afterward like so (I changed the name of fives to ittr, a generic iterator name, to clear up confusion):
int five_count = 0;
vector<long>::iterator ittr;
for (ittr = disqualify.begin(); ittr < disqualify.end(); ittr++)
{
if (*ittr == 5)
++five_count;
}
cout << "Number of times 5 was a disqualifier: " << five_count << endl;
Related
The point of this exercise was to create code that can compute very large sums by using an algorithm close to how you would do it by hand. My code seems to work just fine, except for one specific test case, which is 9223372036854775808 + 486127654835486515383218192. I'm not sure what is special about this specific test case for it to fail, because the code is totally capable of carrying over, as well as adding numbers that have two different amounts of digits...Help would be greatly appreciated.
Edit: The output for this case is +'2+-0+*.4058858552237994000
// Basic mechanism:
//reverse both strings
//reversing the strings works because ex. 12+12 is the same as 21+21=42->reverse->24
//add digits one by one to the end of the smaller string
//dividing each sum by 10 and attaching the remainder to the end of the result-> gets us the carry over value
// reverse the result.
//ex. 45+45 ->reverse = 54+54 -> do the tens place -> 0->carry over -> 4+4+1 -> result= 09 -> reverse -> 90.
#include <iostream>
#include <cstring>
using namespace std;
string strA;
string strB;
string ResStr = ""; // empty result string for storing the result
int carry =0;
int sum; //intermediary sum
int n1; //length of string 1
int n2; // length of string 2
int rem; // remainder
int main()
{
cout << "enter" << endl;
cin >> strA;
cout << "enter" << endl; // I didn't know how to write this program to use argv[1] and argv[2] so this was my solution
cin >> strB;
// turning the length of each string into an integer
int n1 = strA.length(), n2 = strB.length();
if (n1<n2){
swap(strA,strB);
}//for this part I have no idea why this has to be the case but it only works if this statement is here
// Reversing both of the strings so that the ones, tens, etc. positions line up (the computer reads from left to right but we want it to read from right to left)
reverse(strA.begin(), strA.end());
reverse(strB.begin(), strB.end());
for (int i=0; i<n2; i++)//start at 0, perform this operation until the amount of times reaches the value of n2
{
//get the sum of current digits
int sum = ((strA[i]-'0')+(strB[i]-'0')+carry);
int quotient=(sum/10);
int rem=(sum-10*quotient);
ResStr+=(rem+'0'); //this gets the remainder and adds it to the next row
// Calculate carry for next step. Thus works because carry is an integer type, so it will truncate the quotient to an integer, which is what we want
carry = sum/10;
}
// Add the remaining digits of the larger number
for (int i=n2; i<n1; i++) //start at n1, perform this operation until the amount of times reaches the value of n1
{
int sum = ((strA[i]-'0')+carry);
int quotient=(sum/10);
int rem=(sum-10*quotient);
ResStr+=(rem+'0');
carry = sum/10;
}
// Add remaining carry over value
if (carry)
ResStr+=(carry+'0');
// reverse the resulting string back, because we reversed it at the beginning
reverse(ResStr.begin(), ResStr.end());
cout << "The result is " << ResStr << endl;
return 0;
}
After a lot of experimentation, what made the difference for me was replacing n1 and n2 entirely with strA.length() and strB.length() respectively in the for loop declarations. I'm not entirely sure why this happens, so if anyone has an explanation- please forward it.
Anyway, here's my version of the code:
//Basic mechanism: reverse both strings
//reversing the strings works because ex. 12+12 is the same as 21+21=42->reverse->24 (for single-digit sums smaller than 10)
//add digits one by one to the end of the smaller string
//dividing each sum by 10 and attaching the remainder to the end of the result-> gets us the carry over value reverse the result (mod 10 arithetic)
//ex. 45+45 ->reverse = 54+54 -> do the tens place -> 0->carry over -> 4+4+1 -> result= 09 -> reverse -> 90.
//ex. 90+90 ->reverse = 09+09 -> do the tens place -> 0->carry over ->0+ 9+9 ->carry over->1+ result= 081 -> reverse -> 180.
#include <iostream>
using std::cin; using std::cout;
#include <cstring>
using std::string;
#include <algorithm>
using std::reverse;
string strA, strB, ResStr = "";
int carry = 0, sum;
int main() {
//get user input
cout << "Enter first number: "; cin >> strA;
cout << "Enter second number: "; cin >> strB; cout << "\n";
if (length_strA < length_strB){ swap(strA,strB); } //force stringA to be larger (or equal) in size
//Reversing both of the strings so that the ones, tens, etc. positions line up (the computer reads from left to right but we want it to read from right to left)
reverse(strA.begin(), strA.end()); cout << strA << "\n";
reverse(strB.begin(), strB.end()); cout << strB << "\n";
for (int i = 0; i < strB.length(); i++) {
sum = int(strA[i])-48 + int(strB[i])-48 + carry/10;
ResStr += char(sum % 10)+48;
carry = sum - sum%10;
}
// Add the remaining digits of the larger number
//start at strB.length, perform this operation until the amount of times reaches the value of strA.length
for (int i = strB.length(); i < strA.length(); i++) {
sum = int(strA[i])-48 + carry/10;;
ResStr += char(sum % 10)+48;
carry = sum - sum%10;
}
// Add remaining carry over value
if (carry != 0) { ResStr += char(carry)+48; }
// reverse the resulting string back, because we reversed it at the beginning
reverse(ResStr.begin(), ResStr.end());
//return user result
cout << "The result is: " << ResStr << "\n";
return 0; }
To answer why, it's because even once strB ended, it kept iterating through making a new sum in the first loop until strA ended. This meant it was reading null values for strB[i] and adding that to strA[i]+carry- which effectively shifted all the characters into the noisy-looking mess it was.
What the code does:
What this code does is given that number of primes that are wanted, startin from 2 ,it makes an array with those prime numbers. to find the prime numbers what it does is to divide a number that could be a prime by every number on that array, if the remainder in every division isn't 0, that means that is a prime, but if otherwise one of the remainders is 0, that means that isn't a prime , so we continue searching with the next number after it.
The problems:
1. If you delete, in the line 46
cout << ".";
the program gets stuck.
This is like the schrodinger cat, because if I dont use cout, i cant know in what part of the code it gets stuck, and if i use cout, it works
2. When you give numbers, like 1000000, the program is exited with code: -1073741571, why this? well, in line 49 a division of 0/n is done; what is the weird here? well, that part of the code is theorically the same when the number of primes wanted is 1000000 and 1000 when searching the 1000 first prime numbers, and it should make the same, at least ,while finding the first 1000 primes
Finally, the code:
#include<iostream>
using namespace std;
unsigned int primesWanted;
unsigned int possiblePrime=3; //We are going to start searching on the 3
unsigned int primesFound = 1; //We start asigning 2 because later we declare that we have one prime found, the 2
int main(int argc, char* argv[])
{
cout <<"Number of primes wanted?:"<< endl << "=========================" << endl;
cin >> primesWanted;
cout << endl << "========================="<< endl; //the ======== is just for decoration
int primes[primesWanted]; // this is an array that contains all primes found
primes[0]= 2; // We asign the 2 as the first prime found
while(primesFound < primesWanted) // this will be executed until all primes wanted are found
{
cout<< "."; //if you delete this, it doesnt work i dont know why
for (unsigned int i = 1; i <= primesFound; i++)
{
if(possiblePrime % primes[i-1]) //if the number that we are searching remainder is 0 when dividing by a prime, thats mean that could be a prime
{
if(i == primesFound) //if i is equal as the number of primes found, that means that that possiblePrime is a prime
{
primes[primesFound] = possiblePrime; //we add it to the prime list
primesFound++; //we add one because we have added on prime to the list
}
}
else
{
break; //if the number that we are searching remainder is 0 when dividing by a prime, thats mean that is not a prime
}
}
possiblePrime++; //we continue to the next number to search
}
//we print the primes array
cout <<endl << "========================="<< endl;
for (unsigned int i = 0; i < primesFound; i++)
{
cout <<primes[i] << ", ";
}
cout <<endl << "========================="<< endl;
system("pause");
return 0;
}
There is a problem in your code, which when fixed, makes your code run perfectly!
An array MUST have a const value, which means it can't depend on input in any way. It must always be the same.
Change:
int primes[primesWanted];
To:
int* primes = new int[primesWanted];
After all, an array is basically a pointer, so this is the same thing. Now if I remove the cout, it works perfectly and gives an output of:
Number of primes wanted?:
=========================
10
=========================
=========================
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
=========================
Press any key to continue . . .
u can't cin >> primesWanted; because it is size of array which must be const. other way that code works perfectly even without cout<<"."; which is impossible to be problem
I am trying to create a program that will roll 2 dice 10 million times, and output how many times each number is rolled. Along with this, I am tasked with creating a histogram (*=2000) for the outputs.
Here is what I have so far.
/*
Creating a program that counts outcomes of two dice rolls, then show a
histogram of the outcomes.
Section 1 : Simulate ten million times rolls of two dice, while counting
outcomes. (Hint: Use an array of size 13.)
Section 2 : Show the outcome, the numbers of outcomes, and the histogram
(one * designates 20000). Your output must align properly.
*/
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
int i, j, ary[13] = {};
cout << "Please enter the random number seed.";
cin >> j;
srand(j);
for (i = 0; i < 10000000; i++)
ary[die() + die()]++;
for (i = 2; i <= 12; i++)
{
cout << setw(3) << i << " : " << setw(6) << ary[i] << " : ";
for (j = 0; j < ary[i]; j += 2000)
cout << "*";
cout << endl;
}
return 0;
}
EXAMPLE OUTPUT: https://imgur.com/a/tETCj4O
I know I need to do something with rand() % 6 + 1; in the beginning of the program. I feel like I am close to being complete but missing key points! I also realize I have not defnied die() in my ary[]
I recommend creating random seeds from high precision timers such as std::chrono::high_resolution_clock. Then they are not dependent on the user and are actually random. Create the seed always before calling std::rand.
#include <chrono>
auto time = std::chrono::high_resolution_clock::now();
auto seed = std::chrono::duration_cast<std::chrono::milliseconds>(time);
std::srand(seed)
Millisecond precision makes the seed usually unique enough but if the seed is required close to 1000 times a second then i recommend using nanosecond or microsecond precision to be really random.
Best would be to create a function that creates the random seed using high precision timer and the random value and finally makes sure the return value is between 0 and 5 (for 6 sided dice).
The problem's in the title.
If possible please give me exaplanations on what I did wrong and why correct solution is correct.
My attempt at solving it is in the code below... it was supposed get me all the 3 digit numbers then extract digit1, digit2 and digit3 from each number after which it should show the numbers that respect the digit3-digit1==digit2.
The program runs without errors but at the same time it doesn't really do anything.
#include <iostream>
using namespace std;
int main()
{
int Number,digit1,digit2,digit3,h;
for (Number=100; Number<=999; Number++)
{
h=Number;
}
digit1=h/100;
digit2=(h/10)%10;
digit3=h%10;
if (digit3-digit1==digit2)
cout<<digit1<<digit2<<digit3;
return 0;
}
The code that comes after the loop (other than return 0) has to go inside the loop. If it's outside the loop then it only works on the value 999, because that is the last value that h is set to before the loop exits. To print a new line you have to do cout << endl or just place << endl at the end of the print statement before the semicolon.
A few optimizations can be made here. You don't need to loop through all 899 numbers. Given the constraints the the third digit has to be greater than or equal to the first digit, so you can just run a loop for the first digit, and nested loop for the third digit that starts from the first digit.
for (int a = 1; a < 10; a++) {
for (int c = a; c < 10; c++) {
int b = c - a;
cout << a << b << c << endl;
}
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int typedNos;
if (cin >> typedNos)
{
vector <int> inputNos{ typedNos };
while (cin >> typedNos)
{
inputNos.push_back(typedNos);
}
for (decltype (inputNos.size()) n = 1; n < inputNos.size(); ++n)
{
cout << inputNos[0] + inputNos[1] << '\t' << inputNos[(2 * n) - 1]
+ inputNos[(2 * n)] << endl;
return 0;
}
}
else
{
cerr << " Wrong input type or no input was typed!" << endl;
//return -1;
}
}
Everything works fine till the output statement in the for loop is reached. The first two pairs of the vector's elements are manually added to account for zero. The rest are to be added automatically. But this only works for the first pair.
So, for example, an input of:
1 2 3 4 5.
Will give you an output of:
3 5.
Instead of 3 5 7 9.
This is where I have an issue. I have seen other methods of solving this problem but my question is why the sequence 2n (even positions) and 2n-1 (odd positions) do not work for the entire vector? Remember this question does not allow me to use iterators. Thanks.
The problem lies in your for-loop. Using return inside a loop will still exit from the current function. Your current function is main, so this ends the program.
I'm not really sure why you think you need 2 * n. It seems you want to iterate over every object, not every second one.
for (std::size_t n = 1; n < inputNos.size(); ++n) {
std::cout << inputNos[n] + inputNos[n-1] << '\t';
}
std::cout << std::endl;