So i've been attempting this problem for the last few days and have no luck. I am tasked to find square pairs from 1 to x.
Num1 + Num2 = a perfect square (i.e. 2 + 2 = 4. 16 + 20 = 36)
Num2 - Num1 = a perfect square. (i.e. 2 - 2 = 0. 20 - 16 = 4)
I've been getting closer to a result, but for the life of me can not figure out whats going wrong in my loops.
for example: this is my latest approach:
Function to test if a number is a perfect square:
bool isSquare(int num){
if(num < 0)
return false;
int root = round(sqrt(num));
return num == root * root;
}
main:
int num1 = 1; num2 = 2;
int tempP, tempM;
for(int i = 1; i <= number; i++){
for(int j = 1; j <= num1; j++){
tempP = num1 + num2;
tempM = num2 - num1;
if(isSquare(tempP) && isSquare(tempM)){
cout << num1 << "\t" << num2 << "\t" << tempP << "\t" << tempM << endl;
}
num2++;
}
num1++;
}
for some reason my output (regardless of how big 'int number' is) is limited to one row. My other tests(such as having the second loop go until j <= number) end with my num1s repeating themselves, num2s going past number, and printing every number until it stops.
I have no idea where to go next, any pointers would be helpful.
Thank you all
EDIT:
expected output of 12:
N P N + P P – N
2 2 4 0
4 5 9 1
6 10 16 4
8 8 16 0
8 17 25 9
10 26 36 16
12 13 25 1
12 37 49 25
Actual output of 12:
N P N + P P – N
2 2 4 0
num2 is always increasing. You need to reset num2 to an appropriate value at the start of your i loop (before starting the j loop).
The problem is your double loop is incrementing incorrectly. And 1201ProgramAlarm beat me to the punch... num2 never gets reset to 2, so it just keeps growing.
Instead try using the variable from your second loop instead of num2 and see what happens.
Also, comment out or remove num2++;
To avoid brute-force exhaustive searching and checking of squareness, you could use reverse math logic to generate only appropriate pairs. Let
a=num2
b=num1
a >= b > 0
It is known that
a + b = k^2
a - b = m^2
Subtract these equations:
2 * b = k^2 - m^2 = (k-m) * (k+m)
We can see that k and m must have the same oddity - both even or both odd (and b is always even).
So we can enumerate k = 2, 3, 4..., for every k get possible m = k-2, k-4, k-6... and get all (a,b) pairs.
b = (k^2 - m^2) / 2
a = k^2 - b
k m b a
2 0 2 2
3 1 4 5
4 0 8 8
4 2 6 10
5 1 12 13
5 3 8 17
6 0 18 18
6 2 16 20
6 4 10 26
...
One more approach: enumerate even b's, for every b generate all factorizations of b/2 into 2 multipliers p and q (b/2 = p * q, p >= q) and calculate possible variants of k=p+q and a = k^2-b
Example for b=24:
b/2 = 12
p q k a
12 1 13 145
6 2 8 40
4 3 7 25
Your code looks convoluted since i and j increases along with num1 and num2 anyways, so why not combine them?
for (int N = 1; N <= number; N++)
{
for (int P = 0; P <= number; P++)
{
if (ceilf(sqrtf(N+P)) == sqrtf(N+P) && ceilf(sqrtf(P-N)) == sqrtf(P-N))
{
cout << left << setw(10) << N << setw(10) << P << setw(10) << P + N << setw(10) << P - N << endl;
}
}
}
include the cmath library
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;
}
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 doing the problems on Project Euler in C++, but I'm not getting the right answers to the first one.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
int b;
int c;
for (int a = 0; a <= 1000;)
{
a = a + 3;
b = a + b;
}
cout << b << "\n";
for (int a = 0; a <=1000;)
{
a = a + 5;
c = a + c;
}
cout << c << "\n";
b = b + c;
cout << b << "\n";
return 0;
}
My output is:
167835
101505
269340
Where's the error in my logic?
You are adding all values that are both multiples of 3 and 5 (i.e. multiples of 15) twice. Additionally, you will also include 1002 and 1005, which probably isn't intended.
You're double counting numbers that are multiples of 3 and 5 (i.e. multiples of 15).
Consider, Find the sum of all multiples of 3 up to 20?
Ans : =>
3, 6, 9, 12, 15 this are multiples of 3 up to 20
Sum of all multiple of 3 up to 20 is => [3 + 6 +9 + 12 + 15]
(3 + 6 +9 + 12 + 15) you can rewrite in following way
3 (1+ 2+3 +4+5 ) = > 3 (15) => 45
sum of sequence can be calculated using following formula
K(K+1)/2 = > here K is 5 => 5 (5+1)/2 = >15
In general, We can say that multiple of any number (N) within given range R
K = R/N;
N* (K (K+1))/2
In our case R =20 and N =3
int sumDivisibeBy(int R, int N)
{
int K = R / N;
int SEQSUM = ((K*(K + 1)) / 2));
return (N*SEQSUM)
}
In your case you need to call this function thrice =>
sumDivisibeBy(1000,3) + sumDivisibeBy(1000,5)-sumDivisibeBy(1000,15)
Along with double counting multiples of 15, your increments are in the wrong order. If you increment a first, you will have values above 1000. Also I'm not sure about c++ initializing ints, but maybe set them equal to 0, at least for readers.
wouldn't bother incrementing by 3 and by 5, you can increment by 1 and check whether numbers are divisible by 3 or by 5. Computers are designed for number crunching.
int sum = 0;
for (int i = 0; i < 1000; i++)
{
if (i%3 == 0 ||
i%5 == 0)
{
sum += i;
}
}
cout << "SUM:" << sum << endl;
While others have posted exactly where you've erred, you should be trying to figure out how you got the wrong answer as well.
In your case, you could have written all the values you determined to be multiples of 3 and multiples of 5; then you could have analyzed the 333 multiples of 3 you should've seen and the 199 multiples of 5 you should've seen.
I don't want to give away the keys to finding the actual solution (despite the fact that others have already) but part of the problem solving at PE is debugging.
Please help me answer this question , void Function with parameters. I do not understand it very well
I want to write a program so that the user can input both characters that form the pattern
I need to define two (characters) variables which are (star) and (next), the statement must include three parameters – one that will be an (int) for the pattern
and two that will be (characters) for the character to display the pattern.
I have to change the function (drawpattern) to have three values parameters
an (int) parameter indicating the size of the pattern and two (characters) indicating the character that will be used to display the pattern .
input (4) for size, (Y) for the character to be used to start the pattern and (+) for the second and every alternate group
This is what I have done so far and I do not now if is okay:
#include <iostream>
using namespace std;
void drawPattern(int size, char start, char next)
{
for (int i = 0; i <= size; i++)
for (int j = 0; j <= size; j++)
{
if ((i / size) % 3 == 0)
if ((j / size3) % 3 == 0)
cout << '4';
else
cout << 'Y';
else
if ((j / size) % 3 == 0)
cout << '+';
else
cout << '4';
}
}
int main ()
{
int size;
char start, next;
cout << "Please enter number ( 4 ) for the size of the pattern : ";
cin >> size;
cout << " Now enter leter ( Y ) to start the pattern: ";
cin >> start;
cout << "Lastly enter the ( + ) for the other pattern: ";
cin >> size;
cout << " This is the output pattern: " << endl;
drawPattern(size, start, next);
return 0;
}
It looks like you are hard coding your output in the drawPattern function and ignoring the actual input from the user. I think you should probably replace the 'Y' and '+' with the corresponding argument passed to the function, since I'm pretty sure the professor would not be happy about hard coded values.
At line 11, you have a typo. It says size3 where it should say size.
You are also making a logical mistake.
This code
if ((i / size) % 3 == 0)
is wrong in concept. At least as the code is written now. Normally you would write like this:
if (i % 3 == 0)
This if statement will be true every third row. The % (modulu) calculates the remainder of the integer (whole number) division firstnumber / secondnumber. If you have a sequence of i going from 0 to 10, this is what i % 3 outputs
i: 0 1 2 3 4 5 6 7 8 9 10
i%3: 0 1 2 0 1 2 0 1 2 0 1
As you can see, i % 3 == 0 is true when i is divisible by 3.
Your code does something different. Let's say size = 10. Then you calculate the (integer) division i / size. Lastly you calculate (i / size) % 3. However i is always less than size, except at the last turn of the loop. Let's look at the values again:
i: 0 1 2 3 4 5 6 7 8 9 10
size: 10 10 10 10 10 10 10 10 10 10 10
i/size: 0 0 0 0 0 0 0 0 0 0 1
Since the value of i / size only changes once, the calculation (i / size) % 3 is meaningless.