i have this CS question that says:
We will define a series two three to be a series whose first term is some natural number. If the value of the member number n in the series is x, then the value of the (n +1)th member in the series is: (x % 2 ==0) ? x/2 : x*3 +1.
You must write a program that prints two or three series starting with the numbers 1 to twenty-five (not inclusive), but the creation of each series will stop when a value greater than a thousand or a value that has already appeared in a previous series is produced (and therefore the sub-series that was produced from this array onwards has already been produced). The value that is produced must be displayed again, thus stopping the production of the series.
now the code i have written outputs a similar result to the solution output but it needs some changes in order to get the same exact result which i couldn't figure out, this is my code.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int array[25];
for (int i = 1; i < 25; i++)
{
int currentNum = i;
int theNumAfter;
bool occured = false;
while (occured == false)
{
for (int i = 0; i <= 25; i++)
{
if (array[i] == currentNum)
{
occured = true;
cout << endl;
}
}
array[currentNum] = currentNum;
cout << currentNum << " ";
if (currentNum % 2 == 0)
{
theNumAfter = currentNum / 2;
}
else
{
theNumAfter = (3 * currentNum) + 1;
}
array[theNumAfter] = theNumAfter;
cout << theNumAfter << " ";
currentNum = theNumAfter;
}
}
}
the code doesn't take any input and there is only one right output which should be this:
1 4 2 1
2
3 10 5 16 8 4
4
5
6 3
7 22 11 34 17 52 26 13 40 20 10
8
9 28 14 7
10
11
12 6
13
14
15 46 23 70 35 106 53 160 80 40
16
17
18 9
19 58 29 88 44 22
20
21 64 32 16
22
23
24 12
the result of my code:
1 4
4 2
2 1 3 10
10 5
4 2
5 16 6 3
3 10 7 22
22 11 8 4
4 2 9 28 28 14
14 7
10 5
11 34 12 6
6 3 13 40 40 20
20 10
14 7 15 46 46 23
23 70
16 8 17 52 52 26 26 13
13 40 18 9
9 28 19 58 58 29 29 88 88 44 44 22
22 11
what should i change in the code, so we have matching outputs. thanks in advance
the creation of each series will stop when a value greater than a thousand or a value that has already appeared in a previous series is produced.
Up to 24, none of the produced values is greater than a thousand, but the posted code still has an access out of bounds bug:
int main()
{
int array[25];
// ^^
for (int i = 1; i < 25; i++)
{
int currentNum = i;
int theNumAfter;
// ...
array[currentNum] = currentNum;
// ...
array[theNumAfter] = theNumAfter;
// ...
}
// ...
}
Note the many of numbers in the expected output are greater than 25.
I'm not sure what this part was supposed to achive:
for (int i = 0; i <= 25; i++)
{ // ^^^^^^^ it "checks" only the first 25 values that may occur
if (array[i] == currentNum)
{
occured = true;
cout << endl; // <-- The duplicate should be printed before the newline.
// Here it should break out of the loop.
}
}
array[currentNum] = currentNum;
cout << currentNum << " ";
But it fails to produce the expected output.
I'd use a simple array of 1000 bools to memorize the already occurred numbers.
#include <iostream>
int main()
{
constexpr int limit{ 1'000 };
bool already_seen[limit + 1]{};
for (int i = 1; i < 25; i++)
{
int current{ i };
while ( current <= limit and not already_seen[current] )
{
std::cout << current << ' ';
already_seen[current] = true;
if ( current % 2 == 0)
{
current /= 2;
}
else
{
current = (3 * current) + 1;
}
}
std::cout << current << '\n';
}
}
Testable here.
Related
I'm getting a memory access failure while i try to copy the element from my random array.
I have no clue what i am doing wrong, thx for your help in advance.
Here is my code:
1 #include <TSS_API_RNG.h>
2
3 using namespace std;
4
5 // dummy rng for internal speed tests
6 void rng(uint8_t out[], size_t len) {
7
8 unsigned char iv[len];
9 size_t i, k;
10 srand(time(NULL));
11 for (i = 0; i < len; i++) {
12 k = rand()%256;
13 iv[i] = (unsigned char)k;
14 cout << iv[i] << endl;
15
16 memcpy(&out[0], &iv[0], len);
17 cout << &out[0] << endl;
18 memset(&iv[0], 0x00, len);
19 }
20 }
21
22 int main() {
23
24 rng(NULL, 10);
25 return 0;
26 }
And this is what happens when i try to execute my programme:
pi#raspberrypi:~/projects/RNG_final $ ./DUMMY_RNG
▒
Speicherzugriffsfehler
I must be using the memcopy function not correctly, but i have no idea how to solve this issue. For testing i wanted to pass 10 random numbers, but it fails at the first iteration of memcpy. The loop itselfe works properly, hence it prints the value in the first cout value correctly.
Thx guys, managed to fix the issue with your advice.
My code:
1 #include <TSS_API_RNG.h>
2
3 using namespace std;
4
5 // constructor
6 DUMMY_RNG::DUMMY_RNG()
7 :r_len(0), r_count(0)
8 {
9 std::cout << "Neue Instanz" << std::endl;
10 }
11
12
13 // destructor
14 DUMMY_RNG::~DUMMY_RNG(void)
15 {
16 }
17
18
19 // dummy rng for internal speed tests
20 int DUMMY_RNG::rng(uint8_t out[], size_t len) {
21
22 unsigned char iv[len];
23 size_t k;
24 srand(time(NULL));
25 //for (i = 0; i < len; i++) {
26 k = rand()%256;
27 iv[0] = (unsigned char)k;
28
29 memcpy(&out[0], &iv[0], len);
30 memset(&iv[0], 0x00, len);
31 //}
32 return 1;
33 }
34
35
36 // randomize function replacement from botan rng class
37 void DUMMY_RNG::randomize(uint8_t out[], size_t len)
38 {
39 r_count += 1;
40 r_len += len;
41
42 rng(out, len);
43 }
#include <iostream>
long factorial(long n)
{
int x = 1;
for(int i = 2; i <= n; i++) x = x * i;
return x;
}
long nCr(long n, long r)
{
return factorial(n) / (factorial(r) * factorial(n - r));
}
int main()
{
int row;
std::cout << "Enter the number of rows: ";
std::cin >> row;
for (int n = 1; n <= row; n++)
{
for (int s = 1; s <= row - n; s++) std::cout << " "; //space
for (int r = 0; r != n; r++) std::cout << nCr(n-1, r) << " "; //numbers
std::cout << std::endl;
}
}
The code works perfectly fine when constructing a 13-row Pascal's Triangle(albeit a bit ugly), but for some reason it starts becoming inaccurate/wrong at the 14th row and prints this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 4 24 88 221 399 532 532 399 221 88 24 4 1
The purpose of Pascals Triangle is to avoid the calculation of big factorials. See, how many multiplactions you need to make. And by calculating the combinations, n choose k, you quickly come to situations, where build in datatypes overflow.
To tackle such problems, Pascals Triangle is the ideal solution. You can survive, by just summing up values. Row by row.
There are really many solutions for that. I show an example using 2 std::vectors. One holds the current row (the upper row) and the other the next row. For the next row, we can just add the values from the upper row. That is really simple.
Please see:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iomanip>
using ull = unsigned long long;
constexpr size_t NumberOfRows = 50U;
int main() {
std::vector<ull> current{ 1 };
std::vector<ull> next{};
current.reserve(NumberOfRows+2);next.reserve(NumberOfRows+3);
for (size_t i{}; i < NumberOfRows; ++i) {
// Next row has one element more
next.resize(current.size() + 1);
// Each row starts and ends with a 1
next.front() = 1; next.back() = 1;
// For the next row, sum up the upper to values from the current row
for (unsigned k{ 1 }; k < next.size() - 1; ++k)
next[k] = current[k - 1] + current[k];
// Debug Output
std::cout << std::setw(NumberOfRows - i + 2) << "";
std::copy(current.begin(), current.end(), std::ostream_iterator<ull>(std::cout, " "));
std::cout << '\n';
// Prepare next loop run. Assign the calculated row to current
current = std::move(next);
}
return 0;
}
When you calculate factorial(n) you are overflowing LONG_MAX. By doing an unsigned long you get more positive integers but this will only push the maximum rows a few more. If you know that your doing factorial division you can remove a lot of the large numbers by changing the logic.
ie: 13! /11! = (13 * 12 * 11 * 10 * 9....) / (11 * 10 * 9...)
can be simplified to (13* 12) which will remove the overflow
my code fails the tests
Ten towers are given. You need to compare them. exponentiation occurs from right to left a ^ (a ^ (a ^ a)). At the end, print their indexes in ascending order.
input:
10 // number of towers
4 2 2 2 2 2 // 4 The first number in a line is not an element of the tower, it is the //number of elements in it minus one.
1 2 2
1 3 2
1 2 3
3 2 2 2 2
2 2 2 2
1 3 3
3 3 3 3 3
2 4 3 3
2 2 3 4
output:
2 4 3 6 7 5 9 10 1 8
Here is my code but it is incorrect.
#include <fstream>
#include <algorithm>
#include <stdio.h>
#include <math.h>
using namespace std;
class tower_t {
public:
int num; // the tower room
int height; // the height of the tower
double val[11]; // content
double cache[11]; // cache to speed up the calculation
// Designer
tower_t() {
for (int i = 0; i < 11; i++) {
val[i] = 1;
cache[i] = 0;
}
height = 0;
}
// Triple logarithm of the top 3 levels
double head(int level) {
if(cache[level] == 0) cache[level] = log10(log10(val[level])) + log10(val[level + 1]) * val[level + 2];
return cache[level];
}
// The calculation of the tops until intermeddle in double
void normalize() {
while(height > 1 && (log10(val[height - 2]) * val[height - 1]) < 50) {
val[height - 2] = pow(val[height - 2], val[height - 1]);
val[height - 1] = 1;
height--;
}
}
// Output for debugging
void print() {
#ifdef _DEBUG
printf("%2d: {", num);
for (int i = 0; i < height; i++) {
if (i > 0) printf(", ");
if(val[i] < 1000000000) {
printf("%0.0f", val[i]);
} else {
printf("%0.3e", val[i]);
}
}
printf("}\n");
#endif
}
};
// comparison of two towers
bool compare(tower_t& t1, tower_t& t2) {
// floor with which to compare the last three levels
int level = ((t1.height > t2.height) ? t1.height : t2.height) - 3;
if (level < 0) level = 0;
if(t1.height == t2.height) { // if the towers are of the same height, compare by floor
for (int i = t1.height - 1; i >= 0; i--) {
if (abs(t1.val[i] - t2.val[i]) > (t1.val[i] * 1e-14)) {
if (i < level) { // the tops of the towers coincided below level
return t1.val[i] < t2.val[i];
}
break;
}
}
}
return t1.head(level) < t2.head(level);
}
int main(int argc, char**argv)
{
// Reading job
ifstream in ("input.txt");
int cnt;
in >> cnt;
tower_t* towers = new tower_t[cnt];
for (int i = 0; i < cnt; i++) {
int len;
in >> len;
towers[i].num = i + 1;
bool write = true;
for (int j = 0; j <= len; j++) {
int val;
in >> val;
if (val <= 1) write = false; // if level of <= 1 the higher not to read
if(write) {
towers[i].val[j] = val;
towers[i].height = j + 1;
}
}
towers[i].print();
towers[i].normalize();
}
// Sort
sort(towers, towers + cnt, compare);
// The output
ofstream out("output.txt");
for (int i = 0; i < cnt; i++) {
out << towers[i].num << " ";
towers[i].print();
}
out << endl;
out.close();
delete[] towers;
return 0;
}
my code does not pass this test correctly.
23
9 2 2 2 2 2 2 99 2 9 19
9 99 99 99 99 99 99 98 2 9 19
8 25 34 99 75 2 99 99 92 99
7 99 99 78 98 99 90 99 99
5 98 99 99 8 2 34
5 99 99 99 2 2 35
5 98 99 99 16 2 33
4 2 2 4 5 4
3 98 99 98 98
4 4 4 4 4 4
3 3 3 3 3
4 2 2 2 2 2
3 64 2 2 2
3 2 3 2 2
2 4 3 3
3 2 2 2 2
1 3 3
2 2 2 2
1 3 2
1 2 3
0 7
0 5
1 2 2
// correct answer
23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
//my answer
23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 1 2
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to create a program that will find a four-digit number that meets four specific requirements: all four digits are different, the thousands number is 3x the tens number, the number is odd, and the sum of the digits is 27. For some reason, despite the program compiling, the for loop won't run and always outputs the initializer number (1000). My main code and the four functions I'm calling are below. I can't figure out why it won't run correctly. I'm completely new to coding so any tips/help are appreciated. Thanks!
main function:
5 //prototypes
6 bool differentDigits(int);
7 bool thouThreeTen(int);
8 bool numberIsOdd(int);
9 bool sumIs27(int);
10
11 #include <iostream>
12 using namespace std;
13
14 int main ()
15 {
16 //variables
17 int n;
18
19 //processing
20
21 for(n=1000;n<=9999;n++)
22 {
23 if(differentDigits(n)==true)
24 {
25 break;
26 }
27
28 if(thouThreeTen(n)==true)
29 {
30 break;
31 }
32
33 if(numberIsOdd(n)==true)
34 {
35 break;
36 }
37
38 if(sumIs27(n)==true)
39 {
40 break;
41 }
42
43 }
44
45 //output
46 cout << n << endl;
47
48 return 0;
49 }
differentDigits function:
3 //Verify all four digits are the same
4
5 #include <iostream>
6 using namespace std;
7
8 bool differentDigits (int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if(n1 != n2 != n3 != n4)
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }
thouThreeTen function:
3 //Verify digit in thousands place is 3x the digit in tens place
4
5 #include <iostream>
6 using namespace std;
7
8 bool thouThreeTen(int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if(n1 = (n3 * 3))
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }
numberIsOdd function:
3 //Verify that the number is odd
4
5 #include <iostream>
6 using namespace std;
7
8 bool numberIsOdd (int n)
9 {
10 if((n % 2)==1)
11 {
12 return true;
13 }
14 else
15 {
16 return false;
17 }
18
19 }
sumIs27 function:
3 //Verify that the sum of digits is 27
4
5 #include <iostream>
6 using namespace std;
7
8 bool sumIs27(int n)
9 {
10 int n1, n2, n3, n4;
11
12 n1 = n/1000;
13 n2 = (n/100) % 10;
14 n3 = (n/10) % 10;
15 n4 = n % 10;
16
17 if((n1+n2+n3+n4)==27)
18 {
19 return true;
20 }
21 else
22 {
23 return false;
24 }
25
26 }
You have several problems with your code, the first being in main(). If any of the functions return true, you will end the loop. This is probably why you see the for loop as not being executed. Another problem is that in your functions, you are using conditions such as if(n1 = (n3 * 3)) which use the assignment operator instead of checking if they are the same.You want to use if(n1 == (n3 * 3)). Your main should look something like:
int main()
{
int n = 0;
for(n = 1000; n < 9999; ++n)
{
if(differentDigits(n) && thouThreeTen(n) && numberIsOdd(n) && sumIs27(n))
{
break;
}
}
cout << n << endl;
}
In each of your functions, make sure that you are using == not = when you are checking if something is a value.
So I am trying to solve the following question
Input Format is
N
x x x x x ...
q
y y y y y ...
N=size of array
x,x,x ... are elements of array
q=no of queries
y,y,y .. are queries to be searched in the array using binary search
Here is My code
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int N,q;
cin>>N;
int a[N];
for(int i=1;i<=N;i++)
{
cin>>a[i];
}
cin>>q;
int b[q];
for(int i=0;i<q;i++)
{
cin>>b[i];
}
int len=sizeof(a)/sizeof(a[1]);
sort(a,a+len);
int beg=1,end=N;
for(int j=0;j<q;j++)
{
beg=1;end=N;
while(beg<=end)
{
int mid=(beg+end)/2;
if(b[j]==a[mid])
{
cout<<mid<<endl;
break;
}
else if(b[j]<a[mid])
{
end=mid-1;
}
else
beg=mid+1;
}
}
return 0;
}
My code is giving the following output which is wrong
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for the input
100
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
correct output is
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Arrays are 0-based.
Arrays are not variable-length in C++.
You have a wrong update here:
else if(b[j]<a[mid])
{
end=mid-1;
}
The end is non-inclusive.
You will also want to keep going until (beg<end) not beg<=mid - otherwise mid will simply equal both.
Here's C++ version that fixes all of the above and uses iterators instead of indexes. Iterators remove the ambiguity (base-0 vs base-1) and make it very explicit that a range is [begin, end), by contract.
Live ON Coliru
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main() {
int N;
cin >> N;
std::vector<int> a(N);
std::copy_n(std::istream_iterator<int>(std::cin), N, a.begin());
int q;
cin >> q;
std::vector<int> b(q);
std::copy_n(std::istream_iterator<int>(std::cin), q, b.begin());
sort(a.begin(), a.end());
for (auto query : b) {
auto beg = a.begin();
auto end = a.end();
while (beg < end) {
auto mid = beg + (end-beg) / 2;
if (query == *mid) {
cout << *mid << endl;
break;
} else if (query < *mid) {
end = mid;
} else beg = mid + 1;
}
}
}
Prints
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Problem 1
Your program has undefined behavior due to accessing a using an out of bounds index in the following loop.
for(int i=1;i<=N;i++)
{
cin>>a[i];
}
That loop needs to be changed to use a 0 based index.
for(int i = 0; i < N; i++)
{
cin >> a[i];
}
Problem 2
For similar reasons, the initial value of beg needs to be 0, not 1.
Problem 3
You are comparing with values of a[mid] but you are outputting mid. The output also needs to be a[mid].
Problem 4
else if(b[j]<a[mid])
{
end=mid-1;
}
needs to be
else if(b[j]<a[mid])
{
end=mid;
}
With the above changes, the program works as expected in my environment. Here's the updated program:
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int N,q;
cin>>N;
int a[N];
for(int i=0;i<N;i++)
{
cin>>a[i];
}
cin>>q;
int b[q];
for(int i=0;i<q;i++)
{
cin>>b[i];
}
int len=sizeof(a)/sizeof(a[1]);
sort(a,a+len);
int beg=0,end=N;
for(int j=0;j<q;j++)
{
beg=0;end=N;
while(beg<end)
{
int mid=(beg+end)/2;
if(b[j]==a[mid])
{
cout << a[mid] << endl;
break;
}
else if(b[j]<a[mid])
{
end=mid;
}
else
beg=mid+1;
}
}
return 0;
}
See it working at https://ideone.com/wgF2IS.
Array start with 0 index.so make sure for N elements your loop must start with zero index.
for(int i = 0; i < N; i++)
{
cin >> a[i];
}
Similarly, for same reason assign beg '0' value and end 'N-1' value.