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.
Related
Here's the problem statement for what I'm supposed to do:
Write a program to print the following series up to the term input by user.
0, 1, 1, 2, 3, 5, 8, 13, ….
Where 0 is 1st term and 13 is 8th term.
Hint: 0, 1
0+1 = 1
0, 1, 1
1+1 = 2
0, 1, 1, 2
And here's my code:
int prev_i = 0;
cout << "Enter a number: " << endl;
cin >> number;
for (i = 0; i <= number; i++)
{
cout << prev_i + i << " ,";
prev_i = i;
}
I do get what is wrong with my code though. It adds i to prev_i then prev_i is set to i. So in the next iteration when i is 1 thats i + prev_i = 1 so now prev_i = 1 and here's the problem i is 2 now so i + prev_i = 3. And I really can't seem to figure out how to get 1 instead of 3 as the output here and so on.
Oh and don't worry about i not declared properly. I just didn't copy that part.
pls help!
You're trying to generate a fibonacci sequence (starts with two terms (0,1), and each subsequent term is the addition of the prior two). Therefore, i should not be part of the calculation; it is only there to control looping.
A simple generation of the first ten numbers in the sequence is simply this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=0, b=1;
for (int i=0; i<10; ++i)
{
printf("%d ", a);
int c = a+b;
a = b;
b = c;
}
fputc('\n', stdout);
return EXIT_SUCCESS;
}
That's it. The code above will generate the following:
0 1 1 2 3 5 8 13 21 34
I leave applying the above logic to generate whatever your final requirements are up to you, but that's how the sequence is iteratively generated.
PS: Apologies in advance for writing C code. I totally spaced the language tag, but nonetheless the algorithm is the same.
The shown series is the fibonacci sequence.
Look at its definition and find out: Which numbers do you need to compute the current one?
In your current code, you only have one previous number available.
If that's not enough, what else might you need?
Here are my three cents.:)
#include <iostream>
#include <utility>
int main()
{
while (true)
{
std::cout << "Enter a non-negative number (0 - exit): ";
unsigned int n;
if (!( std::cin >> n ) || ( n == 0 )) break;
unsigned long long int first = 0;
unsigned long long int second = 1;
std::cout << '\n';
for (unsigned int i = 0; i < n; i++)
{
if (i != 0) std::cout << ' ';
std::cout << first;
second += std::exchange( first, second );
}
std::cout << "\n\n";
}
}
The program output might look like
Enter a non-negative number (0 - exit): 1
0
Enter a non-negative number (0 - exit): 2
0 1
Enter a non-negative number (0 - exit): 3
0 1 1
Enter a non-negative number (0 - exit): 4
0 1 1 2
Enter a non-negative number (0 - exit): 5
0 1 1 2 3
Enter a non-negative number (0 - exit): 6
0 1 1 2 3 5
Enter a non-negative number (0 - exit): 7
0 1 1 2 3 5 8
Enter a non-negative number (0 - exit): 8
0 1 1 2 3 5 8 13
Enter a non-negative number (0 - exit): 0
Fibonacci numbers grow very quickly. So in general you need to check whether an overflow can occur in the for loop or not.
Your code is printing the sum of current and just previous element. But the above question asks for the Fibonacci number which is define as:
Fib[i] = Fib[i - 1] + Fib[i - 2]; Fib[0] = 0, Fib[1] = 1
Now it can be solved through recursion or 1D DP.
But a simple solution can be constructed by knowing the above relation. We can define the current Fibonacci number is the sum of just previous and previous of just previous.
The code is:
int prev1 = 0; // Fib[0]
int prev2 = 1; // Fib[1]
int curr;
cout << prev1 << ' ' << prev2 << ' ';
for (int i = 2; i <= n; i++)
{
// Fib[i] = Fib[i - 1] + Fib[i - 2];
curr = prev2 + prev1;
cout << curr << ' ';
prev1 = prev2;
prev2 = curr;
}
I wrote a program to print a N x N square pattern with alternate 0's and 1's. For eg. A 5 x 5 square would looks like this:
I used the following code-
#include<iostream.h>
int main()
{
int i, n;
cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
cout << " " << i%2;
if(i%n == 0)
cout << "\n";
}
fflush(stdin);
getchar();
return 0;
}
This code works fine for odd numbers but for even numbers it prints the same thing in each new line and not alternate pattern.For 4 it prints this-
Where am I going wrong?
In my opinion the best way to iterate over matrix is using loop in another loop.
I think this code will be helpful for you:
for(i = 0; i < n; i++) {
for (j = 1; j <= n; j++) {
cout<<" "<< (j + i) % 2;
}
cout<<"\n";
}
where n is number of rows, i and j are ints.
Try to understand why and how it works.
If you're a beginner programmer, then I suggest (no offence) not trying to be too clever with your methodology; the main reason why your code is not working is (apart from various syntax errors) a logic error - as pointed out by blauerschluessel.
Just use two loops, one for rows and one for columns:
for (int row = 1; row <= n; row++)
{
for (int col = 0; col < n; col++)
cout << " " << ((row % 2) ^ (col % 2));
cout << "\n";
}
EDIT: since you wanted a one-loop solution, a good way to do so would be to set a flip flag which handles the difference between even and odd n:
bool flip = false;
int nsq = n * n;
for (int i = 1; i <= nsq; i++)
{
cout << " " << (flip ^ (i % 2));
if (i % n == 0) {
if (n % 2 == 0) flip = !flip;
cout << "\n";
}
}
The reason that it isn't working and creating is because of your logic. To fix this you need to change what the code does. The easiest way to handle that is to think of what it does and compare that to what you want it to do. This sounds like it is for an assignment so we could give you the answer but then you would get nothing from our help so I've writen this answer to guide you to the logic of solving it yourself.
Lets start with what it does.
Currently it is going to print 0 or 1 n*n times. You have a counter named i that will increment every time starting from 0 and going to (n*n)-1. If you were to print this number i you would get the following table for n=5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Now you currently check if the value i is odd or even i%2 and this makes the value 0 or 1. Giving you the following table
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
Now in the case of n=4 your counter i would print out to give you a table
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now if you print out the odd or even pattern you get
1 0 1 0
1 0 1 0
1 0 1 0
1 0 1 0
This pattern diffrence is because of the changing pattern of printed numbers due to the shape of the square or more accurately matrix you are printing. To fix this you need to adjust the logic of how you determine which number to print because it will only work for matrixes that have odd widths.
You just need to add one more parameter to print the value. Below mentioned code has the updated for loop which you are using:
int num = 0;
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
The complete compiled code :
#include <iostream>
#include <stdio.h>
int main()
{
int i, n, num = 0;
std::cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
fflush(stdin);
getchar();
return 0;
}
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.
I tried solving this interview question. My code runs for test cases but fails for all the real input test cases. I tried hard to find the mistake but unable to do so. Please find my code below the question
Bob loves sorting very much. He is always thinking of new ways to sort an array.His friend Ram gives him a challenging task. He gives Bob an array and an integer K. The challenge is to produce the lexicographical minimal array after at most K-swaps. Only consecutive pairs of elements can be swapped. Help Bob in returning the lexicographical minimal array possible after at most K-swaps.
Input: The first line contains an integer T i.e. the number of Test cases. T test cases follow. Each test case has 2 lines. The first line contains N(number of elements in array) and K(number of swaps). The second line contains n integers of the array.
Output: Print the lexicographical minimal array.
Constraints:
1 <= T <= l0
1 <= N,K <= 1000
1 <= A[i] <= 1000000
Sample Input (Plaintext Link)
2
3 2
5 3 1
5 3
8 9 11 2 1
Sample Output (Plaintext Link)
1 5 3
2 8 9 11 1
Explanation
After swap 1:
5 1 3
After swap 2:
1 5 3
{1,5,3} is lexicographically minimal than {5,1,3}
Example 2:
Swap 1: 8 9 2 11 1
Swap 2: 8 2 9 11 1
Swap 3: 2 8 9 11 1
#include <iostream>
using namespace std;
void trySwap(int a[], int start, int end, int *rem)
{
//cout << start << " " << end << " " << *rem << endl;
while (*rem != 0 && end > start)
{
if (a[end - 1] > a[end])
{
swap(a[end - 1], a[end]);
(*rem)--;
end--;
}
else end--;
}
}
void getMinimalLexicographicArray(int a[], int size, int k)
{
int start , rem = k, window = k;
for (start = 0; start < size; start++)
{
window = rem;
if (rem == 0)
return;
else
{
//cout << start << " " << rem << endl;
int end = start + window;
if (end >= size)
{
end = size - 1;
}
trySwap(a, start, end, &rem);
}
}
}
int main()
{
int T, N, K;
int a[1000];
int i, j;
cin >> T;
for (i = 0; i < T; i++)
{
cin >> N;
cin >> K;
for (j = 0; j < N; j++)
{
cin >> a[j];
}
getMinimalLexicographicArray(a, N, K);
for (j = 0; j < N; j++)
cout << a[j] << " ";
cout << endl;
}
return 0;
}
Python solution can be easily translated to C++:
def findMinArray(arr, k):
i = 0
n = len(arr)
while k > 0 and i < n:
min_idx = i
hi = min(n, i + k + 1)
for j in range(i, hi):
if arr[j] < arr[min_idx]:
min_idx = j
for j in range(min_idx, i, -1):
arr[j - 1], arr[j] = arr[j], arr[j - 1]
k -= min_idx - i
i += 1
return arr
Here are two failed test cases.
2
2 2
2 1
5 3
3 2 1 5 4
In the first, your code makes no swaps, because K >= N. In the second, your code swaps 5 and 4 when it should spend its third swap on 3 and 2.
EDIT: the new version is still too greedy. The correct output for
1
10 10
5 4 3 2 1 10 9 8 7 6
is
1 2 3 4 5 10 9 8 7 6
.
I'm trying to code an algorithm that will save to file as binary strings every integer in a range. Eg, for the range 0 to 7:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Note that the leading zeros and spaces between digits are essential.
What I cant figure out how to do in a simple way is to convert the integers to binary numbers represented by bool []s (or some alternate approach).
EDIT
As requested, my solution so far is:
const int NUM_INPUTS = 6;
bool digits[NUM_INPUTS] = {0};
int NUM_PATTERNS = pow(2, NUM_INPUTS);
for(int q = 0; q < NUM_PATTERNS; q++)
{
for(int w = NUM_INPUTS -1 ; w > -1 ; w--)
{
if( ! ((q+1) % ( (int) pow(2, w))) )
digits[w] = !digits[w];
outf << digits[w] << " ";
}
outf << "\n";
}
Unfortunately, this is a bit screwy as the first pattern it gives me is 000001 instead of 000000.
This is not homework. I'm just coding a simple algorithm to give me an input file for training a neural network.
Don't use pow. Just use binary math:
const int NUM_INPUTS = 6;
int NUM_PATTERNS = 1 << NUM_INPUTS;
for(int q = 0; q < NUM_PATTERNS; q++)
{
for(int w = NUM_INPUTS -1 ; w > -1; w--)
{
outf << ((q>>w) & 1) << " ";
}
outf << "\n";
}
Note: I'm not providing code, but merely a hint because the question sounds like homework
This is quite easy. See this example:
number = 23
binary representation = 10111
first digit = (number )&1 = 1
second digit = (number>>1)&1 = 1
third digit = (number>>2)&1 = 1
fourth digit = (number>>3)&1 = 1
fifth digit = (number>>4)&1 = 1
Alternatively written:
temp = number
for i from 0 to digits_count
digit i = temp&1
temp >>= 1
Note that the order of digits taken by this algorithm is the reverse of what you want to print.
The lazy way would be to use std::bitset.
Example:
#include <bitset>
#include <iostream>
int main()
{
for (unsigned int i = 0; i != 8; ++i){
std::bitset<3> b(i);
std::cout << b << std::endl;
}
}
If you want to output the bits individually, space-separated, replace std::cout << b << std::endl; with a call to something like Write(b), with Write defined as:
template<std::size_t S>
void Write(const std::bitset<S>& B)
{
for (int i = S - 1; i >= 0; --i){
std::cout << std::noboolalpha << B[i] << " ";
}
std::cout << std::endl;
}