Output n-th element of the sequence - c++

So here is task.
I tried use this code:
#include <iostream>
#include <istream>
#include <conio.h>
#include <math.h>
using namespace std;
int main(){
int i, n;
cout<<"enter n ";
cin>>n;
if(n==1||n==2){
i=1;
cout<<"\n your number "<<i;
}
else {
for(i=3;i<=n;i++){
i=(i-1)-4*(i-2);
}
cout<<"\n your number"<<i;
}
getch();
}
When enter 1 or 2, I get: "your number 1". But when I enter 3, 5, or 9, I get: "your number 11"
Where is mistake?
And I can't use massive for this task,
because size of massive must be constant number. Not variable
n. Am I right?
Sorry for my english.

I thing that you've got -3 votes because you want us to find the mistake in your code.
As for your Question, you can use recursion:
int f(int x)
{
if(x==1||x==2)
return 1;
else
return =f(x-1)-4*(x-2);
}
int main(){
int x;
cin>>x;
cout<<f(x);
}
I recommend you always to use recursion in sequence when every term but some of the first terms depends on the previous terms.
Recursion will call the function for all terms and add the results to a stack on the memory. it's slower than your way; specially if you want to find the answer for more than one term. but here I thing it's more proper.
If you thought that int would be too small for the result, you could use long long instead.

The way you tried to solve your task is incorrect. You shold keep only 2 last calculated elements in memory, let x(i-1) is a and x(i-2) is b. then you calculate your next value, which well be x(i - 1) on next iteration + move previous x(i-1) to x(i-2) - so your algorithms uses only constant amount of memory. Here is the code:
int calc(int n) {
int a = 1, b = 1;
for(n -= 2; n > 0; --n) {
int tmp = a - 4 * b;
b = a;
a = tmp;
}
return a;
}

Related

How to find Minimum Maximum sum c++

I've written some code in c++ that is meant to find the minimum and maximum values that can be calculated by summing 4 of the 5 integers presented in an array. My thinking was that I could add up all elements of the array and loop through subtracting each of the elements to figure out which subtraction would lead to the smallest and largest totals. I know this isn't the smartest way to do it, but I'm just curious why this brute force method isn't working when I code it. Any feedback would be very much appreciated.
#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;
void minimaxsum(vector<int> arr){
int i,j,temp;
int n=sizeof(arr);
int sum=0;
int low=INT_MAX;
int high=0;
for (j=0;j<n;j++){
for (i=0;i<n;i++){
sum+=arr[i];
}
temp=sum-arr[j];
if(temp<low){
low=temp;
}
else if(temp>high){
high=temp;
}
}
cout<<low;
cout<<high<<endl;
}
int main (){
vector<int> arr;
arr.push_back(1.0);
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
There are 2 problems.
Your code is unfortunately buggy and cannot deliver the correct result.
The solution approach, the design is wrong
I will show you what is wrong and how it could be refactored.
But first and most important: Before you start coding, you need to think. At least 1 day. After that, take a piece of paper and sketch your solution idea. Refactor this idea several times, which will take a complete additional day.
Then, start to write your code. This will take 3 minutes and if you do it with high quality, then it takes 10 minutes.
Let us look first at you code. I will add comments in the source code to indicate some of the problems. Please see:
#include <iostream>
#include <vector>
#include <limits.h> // Do not use .h include files from C-language. Use limits
using namespace std; // Never open the complete std-namepsace. Use fully qualified names
void minimaxsum(vector<int> arr) { // Pass per reference and not per value to avoid copies
int i, j, temp; // Always define variables when you need them, not before. Always initialize
int n = sizeof(arr); // This will not work. You mean "arr.size();"
int sum = 0;
int low = INT_MAX; // Use numeric_limits from C++
int high = 0; // Initialize with MIN value. Otherwise it will fail for negative integers
for (j = 0; j < n; j++) { // It is not understandable, why you use a nested loop, using the same parameters
for (i = 0; i < n; i++) { // Outside sum should be calculated only once
sum += arr[i]; // You will sum up always. Sum is never reset
}
temp = sum - arr[j];
if (temp < low) {
low = temp;
}
else if (temp > high) {
high = temp;
}
}
cout << low; // You miss a '\n' at the end
cout << high << endl; // endl is not necessary for cout. '\n' is sufficent
}
int main() {
vector<int> arr; // use an initializer list
arr.push_back(1.0); // Do not push back doubles into an integer vector
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
Basically your idea to subtract only one value from the overall sum is correct. But there is not need to calculate the overall sum all the time.
Refactoring your code to a working, but still not an optimal C++ solution could look like:
#include <iostream>
#include <vector>
#include <limits>
// Function to show the min and max sum from 4 out of 5 values
void minimaxsum(std::vector<int>& arr) {
// Initialize the resulting values in a way, the the first comparison will always be true
int low = std::numeric_limits<int>::max();
int high = std::numeric_limits<int>::min();;
// Calculate the sum of all 5 values
int sumOf5 = 0;
for (const int i : arr)
sumOf5 += i;
// Now subtract one value from the sum of 5
for (const int i : arr) {
if (sumOf5 - i < low) // Check for new min
low = sumOf5 - i;
if (sumOf5 - i > high) // Check for new max
high = sumOf5 - i;
}
std::cout << "Min: " << low << "\tMax: " << high << '\n';
}
int main() {
std::vector<int> arr{ 1,2,3,1,2 }; // The test Data
minimaxsum(arr); // Show min and max result
}

What is the problem with the logic of the code?

I have been trying to solve this simple problem in C++ but every time I submit, it says wrong answer. I am pretty sure I have got the logic right. Any help is appreciated.
Question: Find the sum of distances between the inputted numbers.
Ex. Input: 2 5 8 2 1
Distance=2+2+5+0
=9, (1 < n < 1000000)
PS: Input can't have the same number consecutively.
PSS: Subtask two is giving Wrong Answer
Code:
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t,a[100000],n,sum=0;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>n;
for(int j=0;j<n;j++)
{
cin>>a[j];
}
for(int j=0;j<n-1;j++)
{
if(a[j]!=a[j+1])
{
sum = sum + abs(a[j]-a[j+1])-1;
}
}
cout<<sum<<endl;
sum=0;
}
}
The problem with your code is that you are using int type for sum whose maximum value (1E11) can exceed the upper limit of int(if it's 32-bit or less). Use long long(atleast 64-bit) instead to store your sum.
Well, you can also optimize the code because you don't exactly need an array of 100000 integers and store the values in it. You can do so using only two variables.
Here is a modified implementation of your logic:
#include <iostream>
int main() {
int t, n, first, second;
long long sum; // or better use std::int_fast64_t sum;
std::cin >> t;
while (t--) {
sum = 0;
std::cin >> n >> first;
for (int i = 0; i < n - 1; ++i) {
std::cin >> second;
sum += std::abs(first - second) - 1;
first = second;
}
std::cout << sum << std::endl;
}
}
PS: In competitive coding checking the provided constraints like if(a[j]!=a[j+1]) is useless. The problem statement simply guarantees it that it will never be false.

How to find Largest Factor of a Number (other than itself) in c++

I am trying to find largest factor of given number its simple but don't why my code not giving correct output:
#include<iostream>
#include<math.h>
#include <bits/stdc++.h>
using namespace std;
int lfactor(int a)
{
int *p;
int s=0;
p=new int[a];
int lf;
for(int i=2;i<a;i++)
{
if(a%2==0)
{
lf=a/2;
cout<<lf;
return 0;
}
else
{
if(a%i==0)
{
p[s]=i;
s++;
}
}
}
cout<<*max_element(p,p+a);
}
int main()
{
int a;
cout<<"Enter Number to calculate largest factor";
cin>>a;
lfactor(a);
}
this code giving me some random output input it am trying 15689
You are getting "random" output because you never initialize the contents of p. What you should be doing is this:
int *p = new int[a] {0}; // fill with zeros
You also never delete this array, so that's a memory leak. You could use a std::unique_ptr<int[]> and not have to worry about deleting it at all.
It's also not necessary to create this array at all. Since you are iterating from the lowest to the greatest number, the most recent factor you found will also be the greatest.
for(int i = 2; i < a; i++)
{
if (a % i == 0) {
lf = i;
s++;
}
}
There are still more ways to optimize this. For example, you could divide by i and start a new loop with fewer iterations if you find that i is a factor of a.

Why am I getting a 'Runtime Error - SIGSEGV' in my code?

I have got some impossible queries for you! (or are they? ;) )
You have n binary numbers of length m. The ith binary number is Bi. Also, you have to perform q queries on them. The indexing is zero-based and the indexing of bits starts from left.
The queries are of type : a, i, j.
If a is:
0 : perform Logical AND operation between Bi and Bj and output the number of 1s in the result.
1 : perform Logical OR operation between Bi and Bj and output the number of 1s in the result.
2 : perform Logical XOR operation between Bi and Bj and output the number of 1s in the result.
3 : flip the value of the jth bit of Bi (i.e. set the bit to 0 if it equals 1 and vice-versa).
Note: For queries of type 0, 1, and 2, the binary numbers remain unchanged.
It is also recommended to use Fast I/O for C++ and JAVA programmers.
Input Format:
First line contains Integers n and m.
The next n lines contain binary numbers of length m.
The ith line contains binary number Bi.
The next line contains an integer q
The next q lines contain queries of type : a, i, j.
Output Format:
Output number of 1s in the result of type 0, 1 and 2 queries.
Constraints:
1<=n, m<=2500
1<=q<=10^6
I have tried changing the array size, but still the error remains the same!
#include <iostream>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m;
cin>>n>>m;
char arr[3000][3000];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
cin>>arr[i][j];
}
long int q;
cin>>q;
char query[3000][3000];
for(long int k=0;k<q;k++)
for(long int l=0;l<3;l++)
{
cin>>query[k][l];
}
for(long int i=0;i<q;i++)
{
if(int(query[i][0]-48)==3)
{
if(arr[int(query[i][1])-48][int(query[i][2])-48]=='1')
{
arr[int(query[i][1])-48][int(query[i][2])-48]='0';
}
else
{
arr[int(query[i][1])-48][int(query[i][2])-48]='1';
}
}
else if(int(query[i][0]-48)==2)
{
int cntr=0;
int bi=int(query[i][1])-48;
int bj=int(query[i][2])-48;
for(int i=0;i<m;i++)
{
int xorres=arr[bi][i]^arr[bj][i];
if(xorres==1)
cntr++;
}
cout<<cntr<<endl;
}
else if(int(query[i][0]-48)==1)
{
int cntr=0;
int bi=int(query[i][1])-48;
int bj=int(query[i][2])-48;
for(int i=0;i<m;i++)
{
int andres=arr[bi][i]|arr[bj][i];
if(andres-48==1)
cntr++;
}
cout<<cntr<<endl;
}
else if(int(query[i][0]-48)==0)
{
int cntr=0;
int bi=int(query[i][1])-48;
int bj=int(query[i][2])-48;
for(int i=0;i<m;i++)
{
int andres=arr[bi][i]&arr[bj][i];
if(andres-48==1)
cntr++;
}
cout<<cntr<<endl;
}
}
return 0;
}
The two char[3000][3000]'s that you allocate on the stack is the reason for the crash.
Since there's no upper constraint on n you'd better to try to allocate it on the heap and catch the exception if it fails. This can be done by using std::vector<std::vector<char>> instead.
Replace:
int n,m;
cin >> n >> m;
char arr[3000][3000];
With something like this:
#include <vector>
size_t n, m;
std::vector<std::vector<char>> arr;
while(std::cin >> n >> m) {
try {
arr.resize(n, std::vector<char>(m));
break; // success, break out of the while-loop
} catch(const std::exception& ex) {
// exception caught, most probably a bad_alloc
std::cerr << ex.what() << " ... try again\n";
}
}
As proposed in the comments, you probably don't need to store all the queries. Just deal with one query at a time.
Also, never #include <bits/stdc++.h> yourself. It's a non-standard/non-portable header file that includes a lot more than you need, and often not all you need. Instead, only include the headers you actually need.
Similarly, using namespace std; is considered bad practice.
OK, so I think you have complicated some things here.
The size of the queries is 10^6 and you are declaring the array as query[3000][3000].
Now, I don't think you need to store the queries. Consider this-
cin>>q;
while(q--)
{
cin>>a>>i>>j;
/*Your code here*/
}
The question states that the queries are in the form : a i j
So for example if you want to perform operation 0 on first 2 strings, the query will be:
0 1 2
But you are storing the binary numbers from index 0!
So, your code will perform the operation on second and third query. So, what you need to do is just take subtract 1 from values of i and j.

Reversing an Array Results In SegFault

#include <iostream>
using namespace std;
/*
*
*/
int main() {
int k, in[k],reversea[k],i,m,n;
cin>>k;
for (i=0;i<k;i++){
cin>>in[i];
}
for (m=k-1;m>=0;m--){
for (n=0;n<k;n++){
in[m]=reversea[n];
}
}
for(i=0;i<k;i++){
cout<<reversea[i];
}
return 0;
}
I have no idea why it says segmentation fault even before i start debugging it. I compile another one on calculating the frequency of 1, 5, and 10 in an array of k numbers, and it says the same thing...
Here is the other one:
#include <iostream>
using namespace std;
int main() {
int k,i,m,n,count5,count1,count10;
int input[k];
cin>>k;
for (i=0;i<k;i++){
cin>>input[i];
}//input all the numbers
for(i=0;i<k;i++){
if (input[i]=1){
count1++;
}
if (input[i]=5){
count5++;
}
if (input[i]=10){
count10++;
}
}
cout<<count1<<"\n"<<count5<<"\n"<<count10<<"\n";
return 0;
}
Please help me. Thanks.
On this line
int k, in[k],reversea[k]
How are you supposed to initialize an array with k elements if k isn't initialized? The size of an array must be known at compile time not run time. If k isn't know until run time, use a std::vector
int k;
std::cin >> k;
std::vector<int> in(k);
std::vector<int> reversea(k);
Both your programs have two major faults.
You need to know the size of an array while creating it. In your code, k is still uninitialized and you are using this value as the size of your array. Instead, change it to
int k,i,m,n;
cin >> k;
int in[k];
int reversea[k];
While reversing the array, you should be filling reversea using values from in, and not the other way round. Also, you don't need 2 for loops, just use 1 for loop.
for (m=k-1; m>=0; m--){
reversea[m] = in[k-1-m];
}
In the second program, you again need to get the value of k before creating the array input[k].
You are testing for equality with a = instead of == . Change your code from
if (input[i]=1){
to
if (input[i] == 1) {