With the help of some people on here I managed to find the stopping values for a range of initial values 1 to 1000 in the Collatz function. Collatz function
(My mistake was sorted by using a new variable say s instead of c in the for loop and then letting c=s).
I am now trying to produce code to keep track of the maximum stopping value (count) for these initial values (1 to 1000) and then output it at the end. Could anyone give me some pointers if they know how to do this?
Thanks.
Define a maximum of zero before running the loop the first time. Then check if your stop value is greater than the current maximum value: If so set the current maximum to the current stop. Repeat this every time you found a stop value.
#include <iostream>
using namespace std;
int main()
{
long max = 0;
for(long c=2, c<=1000; c++) // define stopping value as 0 for c=1 elsewhere
{
long count=0;
while (c!=1)
{
if((c%2)==0)
{
c/=2;
}
else
{
c=3*c+1;
}
count ++;
}
if ( count > max ) max = count;
cout << "The stopping value for " << c << " is " << count << endl;
}
cout << "The max stopping value is " << max << endl;
return 0;
}
Related
I am new to coding and my task is to make the variable 'sum' greater than (not equal to) m by summing up 1/n for an increasing 'n'.
I need to solve the same problem twice (one using a for-loop and once using a while-loop). But both ways end in an infinte loop.
My code is working fine when I replace the "<=" with "<". But that
Can someone help me?
#include <iostream>
using namespace std;
int main () {
unsigned int m = 1;
double sum = 0;
long n;
n = 1;
while (sum <= m) //THIS LINE
{
double sumsum = 1/n;
sum += sumsum;
n++;
}
cout << "n = " << n << endl ;
cout << "sum = " << sum << endl ;
return 0;
}
Epression 1/n with n being of type long and having a value > 1 will always yield 0, since you operate with integral types. Hence, sum will be assigned 1 in the first run, but will never come to a value > 1, as forth on always 0 is added.
Change your code to
double sumsum = 1.0/n;
and it should work. Note that 1.0 enforces to operate with floating points.
The purpose of this program is to be able to input a set of integer double values, and for it to output the total distance as a sum. It's also meant to recognize the smallest and largest distances -- as well as calculate the mean of two or more distances.
I would also like to be able to remove the repetitive block of code in my program, which I've literally copied to get the second part of the source code working. Apparently there's a way to remove the replication -- but I don't know how.
Here's the source:
/* These includes are all part of a custom header designed
by Bjarne Stroustrup as part of Programming: Principles and Practice
using c++
*/
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
// I am also using the "stdafx.h" header.
// reading a sequence of integer doubles into a vector.
This could be the distance between two areas with different paths
int main()
{
vector<double> dist; // vector, double integer value
double sum = 0; // sum of two doubles
double min = 0; // min dist
double max = 0; // max dist
cout << "Please enter a sequence of integer doubles (representing distances): \n";
double val = 0;
while (cin >> val)
{
if (val <= 0)
{
if (dist.size() == 0)
error("no distances");
cout << "The total distance is: " << sum << "\n";
cout << "The smallest distance is: " << min << "\n";
cout << "The greatest distance is: " << max << "\n";
cout << "The average (mean) distance is: " << sum / dist.size() << "\n";
keep_window_open();
return 0;
}
dist.push_back(val); // stores vector value
// updating the runtime values
sum += val;
if (val > min)
min = val;
if (max < val)
max = val;
}
if (dist.size() == 0)
error("no distances");
cout << "The total distance is: " << sum << "\n";
cout << "The smallest distance is: " << min << "\n";
cout << "The greatest distance is: " << max << "\n";
cout << "The average (mean) distance is: " << sum / dist.size() << "\n";
keep_window_open();
}
Additionally, I have been trying to input a small block of source code in the form of something like "catch (runtime_error e)" but it expects a declaration of some sort and I don't know how to get it to compile without errors.
Help with removing the replicated/repeating block of code to reduce bloat would be great -- on top of everything else.
Instead of having the if statement inside the while, you should combine the two conditions to avoid duplicating that code:
while ( (cin >> val) && (val > 0) )
Also, you need to initialize min to a largest value, rather than zero, if you want the first comparison to capture the first possible value for min.
Making a function out of duplicated code is a general purpose solution that isn't a good choice in your case for two reasons: First, it isn't necessary, since it is easier and better to combine the flow of control so there is no need to invoke that code in two places. Second there are too many local variables used in the duplicated code, so if there were a reason to make the duplicated code into a function, good design would also demand collecting some or all of those local variables into an object.
If it had not been cleaner and easier to merge the two conditions, it still would be better to merge the flow of control than to invent the function to call from two places. You cold have used:
if (val <= 0)
{
break;
}
I have this program to write that I have a array of 11 numbers entered from me. Then I need to find the avarage sum of those numbers, and then im asked to find the closest number of this array to the avarage sum, and then the most distant element of the array to the avarage sum again. SO far I manage to write a program to create this array and find the avarage sum. I asssume there is something to do with abs function of cmath libary , but so far I only fail to make it.
#include <iostream>
using namespace std;
int main() {
unsigned const int size = 11;
float number[size];
for (unsigned i = 0; i<size; i++) {
cout << "Please enter value for number "
<< i + 1 << ":";
cin >> number[i];
}
for (unsigned i = 0; i<size; i++) {
cout << "Number " << i + 1 << " is : "
<< number[i] << endl;
}
unsigned int sum = 0;
for (unsigned i = 0; i<size; i++) {
sum += number[i];
}
What is the problem? You are not asking a question, just making a statement... It does seem that you have not posted the whole code..
In c++ usually to use "abs" you should use fabs from the "math.h" library!
You will be okay with the compare operators.
Just traverse your array in a loop and calculate the difference between your compare value and the current value on your array. Initiate a temporary variable that keeps the array entry that created the smallest difference.
Every time a difference that is smaller than the current one comes up replace the value in your temporary variable.
So you replace under the following condition: If |number[i] - average_value| < |tmp_closest_val -average_val| Then tmp_closest_val = number[i] EndIf.
I hope you get the concept from that rough draft.
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;
I was wondering if anyone can help me with something I was struggling all day with.
In the code below I dictated an array of randomized numbers from which I have to have pull out the max the min and the average. It all looks fine and good (such a compact software!) But I attain a weird output. I believe I have a finger on what the problem is (say I'm finding the max for the first number but the next number is smaller the software will think that's the biggest number even though integer 14 may be bigger) but I have no idea how to go about fixing this. The minimum value I have no idea why it's wrong it keeps saying it's zero and the average value stays anywhere from 10-19 which is impossible considering the range of randomized numbers goes from 1 to 1000. I was never taught how to organize random numbers in an array, so I just have no idea how to go about fixing this. Any help will be super awesome! I really struggled with this program and even scrapped it multiple times, if it's only a simple mistake I overlooked I would feel awfully embarrassed I'll post the code and an example output below.
Thanks for taking your time, I hope you have a wonderful day!
#include <cmath>
#include <iostream>
#include<cstdlib>
#include <ctime>
#include <time.h>
#include <iomanip>
using namespace std;
int main()
{
//Defining variables
//DEFINE SIZE
const int ARRAY_SIZE =20;
//Index variable
int i;
//For finding average
double sum=0;
double max_value;
double min_value;
//Keep all numbers sane
cout.precision(5);
srand((unsigned)time(0));
double main_array[ARRAY_SIZE];
//Header
cout << "Element number \t\t" << "Random Number\n\n" << endl;
//Assigning random values into array.
for (i=0; i< ARRAY_SIZE; i++)
{
max_value=0;
min_value=0;
//Randomizer
double ran = 0 + (rand()/((float)RAND_MAX/(1000-0)));
main_array[i] = ran;
cout << "\t" << i << "\t\t" << main_array[i] << endl;
//Find average
sum= (sum + main_array[i]);
sum= sum/(ARRAY_SIZE+1);
//Initalizing
for (int i = 0; i < ARRAY_SIZE; i++)
{
if ( min_value > ran)
min_value = main_array[i];
if (max_value < ran)
max_value = main_array[i];
}
}
cout <<"Average Value is: " << sum << endl;
cout <<"\nThe Minimum Value Is: " << min_value << endl;
cout <<"\nThe Maximum value Is: " << max_value << endl;
system ("pause");
return 0;
}
An output example would be
Element number Random Number
0 791.62
1 542.04
2 879.57
3 875.39
4 38.057
5 73.702
6 973.27
7 22.431
8 830.26
9 444.59
10 276.89
11 888.12
12 827.17
13 900.45
14 883.72
15 201.15
16 317.64
17 649.83
18 443.98
19 683
Average Value is: 33.603
The Minimum Value Is: 0
The Maximum value Is: 791.62
Press any key to continue . . .
Unless you must do otherwise, use std::min_element to find the minimum, std::max_element to find the maximum, and std::accumulate to find the sum.
If you absolutely must do this on your own, you usually want to initialize your minimum and maximum to the first element in the collection, then look for others that are smaller/larger:
int mininum = array[0];
int maximum = array[0];
for (int i=1; i<array_size; i++) {
if (array[i] < minimum)
minimum = array[i];
if (array[i] > maximum)
maximum = array[i];
}
Before you start looping, create a min, max, and total. Then when you are creating each element of the array, also check whether it is less than the min or more than the max. Also add that number to your total. At the end, outside the loop, divide the total by the number of elements to get your average.
You definitely shouldn't be iterating through the whole array each time you add an element, and you shouldn't be resetting your min and max each time through the loop. You also shouldn't set your min to 0 if all your numbers are going to be more than 0, because it will never be updated.