How to solve the "Utopian Tree" - c++

The Utopian Tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian Tree sapling is planted at the onset of spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
#include <iostream>
using namespace std;
int height(int n) {
int h[61],i;
h[0]=1;
for(i=1;i<61;i++)
{ if (i%2!=0)
h[i]=h[i-1]*2;
else h[i]=h[i-1]+1;
}
cout<<h[n];
return 0;
}
int main() {
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
cout << height(n) << endl;
}
}

Here is a simple solution that avoids too much calculations.
Notice the following:
n: Height: Hint:
0 1 2^0
1 2*1=2 2^1
2 2+1=3 2^2 -1
3 2*3=6 2^3 -2
4 6+1=7 2^3 -1
5 2*7=14 2^4 -2
6 14+1=15 2^4 -1
7 2*15=30 2^5 -2
8 30+1=31 2^5 -1
9 2*31=62 2^6 -2
10 62+1=63 2^6 -1
11 2*63=126 2^7 -2
12 126+1=127 2^7 -1
13 2*127=254 2^8 -2
14 254+1=255 2^8 -1
15 2*255=510 2^9 -2
16 510+1=511 2^9 -1
and so on and so forth...
That means that we can use bit shift and avoid for loops etc. Here is a simple solution:
int main(){
//number of test cases
int t;
cin >> t;
for(int i= 0; i< t; ++i){
//number of cycles for the tree growth
int n;
cin >> n;
if (n == 0)
cout << 1 << endl;
else if (n == 1)
cout << 2 << endl;
else if (n > 1){
cout << ((1 << ( (n & 1) ? ((n+1)/2) : (n/2)) + 1) - ((n & 1) ? 2 : 1)) << endl;
}
}
return 0;
}
The key is to categorize number of cycles in odd and even and process accordingly.

You should return h[n] instead of 0 here:
int height(int n) {
int h[61],i;
h[0]=1;
for(i=1;i<61;i++)
{ if (i%2!=0)
h[i]=h[i-1]*2;
else h[i]=h[i-1]+1;
}
//cout<<h[n]<<endl;
return h[n];
}
Also, note that it was printing 10 and 20 because the value of h[n] was actually 1 and 2 itself but the function was returning 0 itself.
Due to the statement:
cout << h[n];
It was printing 1(and 2 for next call) and then due to statement:
cout<<height(n);
it was printing the 0(and 0 for next call). Thus, it was printing 1 and 0 for height[0] and then printing 2 and 0 for height[0] .
Summary:
Return h[n] from function instead of 0.
Also, use tab or newline with cout to minimize the confusion.
Why to print the value in both height() and main(). Simply do it in main()

The code should produce 10 and 20 based on your program if you enter 2 0 1. You might want to have a look at what you output and what you return from your function plus what you do with the result.
Note that you should also always check that your inputs were actually successful e.g. using if (std::cin >> T) { ... }. However, that's not the problem in your code.

The function int height(int ) should return h[n]; instead of printing h[n] (cout << h[n];) and then return 0 (which adds 0 next to your desired output of 1,2). Using your code, you should modify it as follows in order to make it work:
#include <iostream>
using namespace std;
int height(int n) {
int h[61],i;
h[0]=1;
for(i=1;i<61;i++)
{ if (i%2!=0)
h[i]=h[i-1]*2;
else h[i]=h[i-1]+1;
}
//cout<<h[n];
return h[n];
}
int main() {
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
cout << height(n) << endl;
}
}

How about array of functions?
typedef int(*FunctionPrt)(int);
int utopianTree(int n) {
int initialHeight = 1;
FunctionPrt functions[] = {
[](int initialHeight) { return initialHeight * 2; },
[](int initialHeight) { return initialHeight + 1; }
};
for (int cycles = 0, i = 0; cycles < n; i = (i + 1) % 2, ++cycles) {
initialHeight = functions[i](initialHeight);
}
return initialHeight;
}

Related

Josephus Problem Clockwise find the Safe Position base on the number of people(n) is there anyway to improve the code?

According to Numberphile if (n) number of soldiers is a power of 2 regardless of starting position the answer will always be the starting position
please refer to this image... and if not please refer to this image i hope you understand my simple illustration on the problem thank you...
/*
formulas: *1 if (n) is power of 2 then the answer is 1
*W(n) = 2l + 1
version 0.4
*/
#include<iostream>
#include<string>
using namespace std;
bool isPowerofTwo(int n){
return (n & (n - 1)) == 0;
}
int bin_to_dec(long n){
int dec = 0, i = 0, rem, base = 1;
while (n != 0) {
dec += (n % 10) * base;
n /= 10;
base *= 2;
}
return dec;
}
int main(){
//var1: input of (n) var2: bin as "binary var3: str for string"
unsigned int n, i, bin;
string str;
cout<<"Input (n): ";
cin>>n;
if(isPowerofTwo(n)){
cout<<"The safe position is no. " << 1 << endl;
} else {
while(n!=0){//decimal to binary conversion
str = (n % 2 == 0 ? "0":"1") + str;
n/=2;
}
str.erase(0,1); //erasing the largest binary (the leftmost because it is not needed)
bin = stoi(str); //converting string to int
cout<<"The safe position is no. " << (bin_to_dec(bin) * 2) + 1; //converting binary to get the 2l+1
}
return 0;
}
#include<math.h>
bool isPowerofTwo(int n){
return (ceil(log2(n)) == floor(log2(n)));
}
The definition of ceil() is double ceil(double x);. Same goes for floor() and log2(). You are calling some expensive floating point functions here that are also inprecise.
bool isPowerofTwo(usigned int n) {
return (n & (n - 1)) == 0;
}
Subtracting 1 will turn the lowest 1 bit in n into a 0. The bitwise AND then eliminates the lowest 1 bit in n. If n is a power of 2 then it has only 1 bit set. That means the AND gives 0.
In main also use unsigned int for everything that can't be negative. It often produces simpler code, like for example n % 2 can be complicated if the cpus % operation gives different results for negative numbers than the standard requires (or you use MSVC and it thinks that's the case).

Getting unknown values along with answer

Smaller Greater Equal Numbers
PrepBuddy has N baskets containing one fruit each with some quality factor(ith basket have Ai quality factor) and Tina has one single basket with one fruit having quality factor K. She wants to know how many PrepBuddy's baskets have quality factor less(L) than K, how many baskets have quality factor more(M) than K and how many baskets have quality factor equal(E) to K.
Input format
The first line contains an integer T, representing the number of test cases.T test cases follow,First linecontains two space-separated integers N and K.The second line contains N space-separated integers representing the quality factor of the basket.
Output format
For each test case on a new line, print three space-separated integers representing the values of L, M,and E.
Constraints
1<=T<=100
1<=N,K<=10^5
−10^6<=A[i]<=10^6
Sum of all N over any test case file doesn't exceed 5∗10^6
Time Limit
1 second
Example
Input
2
5 2
-1 0 -3 1 2
5 3
1 -1 -5 2 4
Output
4 0 1
4 1 0
Sample test case explanation
In the first test case,
K=2, the baskets with quality factor smaller than K are [1,2,3,4], there is no basket which has quality factor more than K and there is one basket [5] which have quality factor equal to K.
My solution
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
ll n, k;
cin >> n >> k;
ll arr[n];
for (ll i = 0; i < n; i++) {
cin >> arr[i];
}
int less = 0, more = 0, equal = 0;
for (ll i = 0; i < n; i++) {
if (arr[i] < k) {
less++;
} else if (arr[i] > k) {
more++;
} else {
equal++;
}
cout << less << " " << more << " " << equal << " ";
}
cout << endl;
}
return 0;
}
Input
2
5 2
-1 0 -3 1 2
5 3
1 -1 -5 2 4
Output
1 0 0 2 0 0 3 0 0 4 0 0 4 0 1
1 0 0 2 0 0 3 0 0 4 0 0 4 1 0
Why am I getting additional numbers like 1 0 0 2 0 0 3 0 0 4 0 0 along with my answer.How to correct this?? Please help
The error in your code was quiet simple, and easy to debug. You were printing the output every run through the array, thus, getting all these extra prints.
How does it become easy to debug? Reorganizing the code so it will be more readable, made it quiet possible. Actually, the fix was moving the line:
cout<<less<<" "<<more<<" "<<equal<<" ";
Two line lower than it was.
In order to demonstrate it, here is the code fixed and organized:
#include <iostream>
#include <vector>
#include <cstdint>
int main()
{
int t;
std::cin >> t;
while(t--)
{
std::int64_t n,k;
std::cin >> n >> k;
std::vector<int> vec{n};
for(std::size_t i = 0; i < n; ++i)
{
std::cin >> vec[i];
}
int less=0, more=0, equal=0;
for (std::size_t i = 0; i < n; i++)
{
if (vec[i] < k)
{
less++;
}
else if (vec[i] > k)
{
more++;
}
else
{
equal++;
}
// The next output line was here, under the for loop!!!
}
std::cout << less << " " << more<< " " << equal << " "; // this is its place!
std::cout << std::endl;
}
return 0;
}
I have made only 3 changes:
Removed the using namespace std; and #include <bit/stdc++.h>.
Realigned the code according to its logical order - each new scope has its own indentation level, showing which command runs in which scope, revealing the mistake.
Used proper types to each thing: In C++ there are no dynamic arrays in the format arr[n], thus, you need to use std::vector. Also, there are fixed size lengths in cstdint, and you should use those to ensure you are using the right type. Also, prefer using unsigned values when possible, for example, when indexing, use either std::size_t, std::uint32_t or std::uint64_t.
This code worked fine for me
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T,N,K,arr[N];
cin>>T;
while(T--)
{
cin>>N;
cin>>K;
for(int i=0;i<N;i++)
{
cin>>arr[i];
}
int L=0,M=0,E=0;
for(int i=0;i<N;i++)
{
if(arr[i]<K){
L++;
}
else if(arr[i]>K)
{
M++;
}
else{
E++;
}
}
cout<<L<<" "<<M<<" "<<E<<endl;
}
return 0;
}

Weird Input output in cpp

I was solving subarray with given sum,Where we have to print the starting and ending index of array if subarray with sum is found , when I tried with two test cases simultaneously i got wrong result
But when I was tried one at a time I got right answer in both.
You please also check in your IDE this is happening in every IDE.
Testcase (Simultaneously)
2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10
Output
2 4 (expected 2 4)
2 5 (But expected 1 5)
But when I tried like this for second test cases
1
10 15
1 2 3 4 5 6 7 8 9 10
Output : 1 5(As expected)
I got correct answer ,why my program this kind of weird behaviour ?
#include<iostream>
#include<vector>
#include<queue>
#include<unordered_map>
using namespace std;
vector<int>a;
unordered_map<int, int>seen;
int main()
{
int t;
cin >> t;
while (t--) {
int n, s;
cin >> n >> s;
a.resize(n);
int sum = 0;
seen[0] = -1;
for (int i = 0; i < n; i++) {
cin >> a[i];
sum += a[i];
if (seen.find(sum - s) != seen.end()) {
int x;
x = seen[sum - s] + 2;
cout << x << " " << i + 1 << endl;
break;
}
else {
seen[sum] = i;
}
}
seen.clear();
a.clear();
//cout<<endl;
}
return 0;
}

using a user input in a loop and function

My program takes a user input, int n, and prints out the first n amount of prime numbers. This is working as intended
eg. if user inputs 8 as n. the program will print :
2 3 5 7 11 13 17 19
My problem is adding the function isPrime(n) (which is not allowed to be changed)
here is what i've tried but im just getting the output :
2 3 5 7 11 13 17 19 0 is not a prime number,
when it should read 2 3 5 7 11 13 17 19 8 is not a prime number
#include "prime.h"
#include <iostream>
int main()
{
int n;
std::cout << "Enter a natural number: ";
std::cin >> n;
for (int i = 2; n > 0; ++i)
{
bool Prime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
Prime = false;
break;
}
}
if (Prime)
{
--n;
std::cout << i << " ";
}
}
if (isPrime(n))
{
std::cout << n << " is a prime number." << std::endl;
}
else
{
std::cout << n << " is not a prime number." << std::endl;
}
system("pause");
}
prime.h :
#ifndef PRIME_H_RBH300111
#define PRIME_H_RBH300111
bool isPrime(int);
#endif
#pragma once
the definition of isPrime(int)
prime.cpp :
#include <cmath>
#include "prime.h"
bool isPrime(int n)
{
if (n < 2)
{
return false;
}
else if (n == 2)
{
return true;
}
else if ((n % 2) == 0)
{
return false;
}
}
I cannot alter the .h file of prime.cpp
I just need the isPrime(n) function to work on the main() function code
the user input n, does not seem to be taking the number 8. but instead 0
giving me the output. 0 is not a prime number
rather than : n (8) is not a prime number
You are decrementing n in the loop. At the time the loop exits, the value of n is 0.
You can solve the problem by:
Using another variable to use in the loop.
Keeping a copy of the n and resetting the value of n after the loop exits.
Here's the second method:
int copyN = n;
for (int i = 2; n > 0; ++i)
{
...
}
n = copyN;
if (isPrime(n))
...
You are decrementing n in the for loop. The for loop has the condition 'n > 0', so you know n isn't > 0 when the loop finishes. You could either save the value of n in a different variable (i.e. "int nOrig = n;") and use that for the prime test, or use a different variable in the loop.

Are i < N+1 and i <= N different?

I used to know that There is no difference between i <= N and i < N+1
However, when I enter 6 6 to program.
if i <= N then it print
1 6 6 6 1 1 2 3 3 3 2 2
otherwise
1 6 6 6 1 1 2 3 3 3 2 2 3 2 2 2 3 3
I can't figure out why it make a difference
#include <iostream>
#include <cmath>
using namespace std;
typedef long long LNT;
LNT gcd(LNT a, LNT b)
{
if( b == 0)
return a;
return gcd(b, a%b);
}
int main()
{
LNT red, green;
LNT GCD;
cin >> red >> green;
GCD = gcd(red, green);
//for(LNT i = 1; i<sqrtl(GCD)+1; i++)
for(LNT i = 1; i<=sqrtl(GCD); i++) // <- This Line cause the difference
{
if( GCD % i == 0)
{
cout << i << " " << red/i << " " << green/i <<endl;
if( i != GCD/i )
{
LNT k = GCD/i;
cout << k << " " << red/k << " " << green/k <<endl;
}
}
}
}
This is true only for integer values. As sqrtl returns long double, in case it's fractional then for the fraction it will still differ if you compare original with fraction and +1 where one another integer fits:
! 2 <= 1.5
2 < 1.5+1
sqrtl return long double in this case your assumption:
no difference between i <= N and i < N+1
is wrong.
well,there is no difference between i<=n and i < n+1 as both of them runs till only n but what u doing is sqrt which returns long double and for them not necessarily to be same.