The input for this problem is a first number that indicates how many cases will be input to be analyzed.
Input:
3
8 12
9 27
259 111
The first number means that there will be 3 cases. The next 3 lines are the cases. The program has to output the GCD (Greatest Common Divisor) of the 3 cases.
4
9
37
The code I wrote looks like the following:
#include <iostream>
#include <vector>
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int main() {
int N;
std::cin >> N;
int i = 0;
std::vector<int> cards;
while (i <= N) {
i++;
int F1, F2;
std::cin >> F1 >> F2;
cards[i] = gcd(F1, F2);
}
for (int j; j <= N; i++) {
i++;
std::cout << cards[i] << "\n";
}
}
It reads the first integer (number of test cases), runs the loop once (reads one test case) and stops running. The terminal outputs exited, segmentation fault. What is the problem?
In your code there are some problem, first of all you haven't setted the size of the vector, that result like it has 0 lenght.
Another error are the loops;
In fact in the firts one you add 1 to i before you do all the other operation, and in this way you'll start to insert from te second component of the vector (vector start his indexing at 0).
Also in the second loop there are some problems, for example you declare a variable j that it is totally usless becouse in the folowing operations you still use i (that is setted at the end value of the previous loop, the while one).
Try to correct this things and understand it and in this way you'll understand also the reason of your error, that is pretty common in c++.
I hope that i've helped you a bit :)
Related
I'm trying to solve Codewars task and facing issue that looks strange to me.
Codewars task is to write function digital_root(n) that sums digits of n until the end result has only 1 digit in it.
Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 (the function returns 6).
I wrote some bulky code with supporting functions, please see code with notes below.
The problem - digital_root function works only if I put cout line in while loop. The function returns nonsense without this cout line (please see notes in the code of the function).
My questions are:
Why isn't digital_root working without cout line?
How cout line can effect the result of the function?
Why does cout line fix the code?
Thanks a lot in advance! I'm a beginner, spent several days trying to solve the issue.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int getDigit (int, int);
int sumDigits (int);
int digital_root (int);
int main()
{
cout << digital_root (942); // expected output result is 6 because 9 + 4 + 2 = 15 -> 1 + 5 = 6
}
int getDigit (int inputNum, int position) // returns digit of inputNum that sits on a particular position (works)
{
int empoweredTen = pow(10, position-1);
return inputNum / empoweredTen % 10;
}
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum;
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
int digital_root (int inputNum) // supposed to calculate sum of digits until number has 1 digit in it (abnormal behavior)
{
int n = inputNum;
while (n > 9)
{
n = sumDigits(n);
cout << "The current n is: " << n << endl; // !!! function doesn't work without this line !!!
}
return n;
}
I've tried to rewrite the code from scratch several times with Google to find a mistake but I can't see it. I expect digital_root() to work without any cout lines in it. Currently, if I delete cout line from while loop in digital_root(), the function returns -2147483647 after 13 seconds of calculations. Sad.
Here is an implementation using integer operators instead of calling std::to_string() and std::pow() functions - this actually works with floating-point numbers. It uses two integer variables, nSum and nRem, holding the running sum and remainder of the input number.
// calculates sum of digits until number has 1 digit in it
int digital_root(int inputNum)
{
while (inputNum > 9)
{
int nRem = inputNum, nSum = 0;
do // checking nRem after the loop avoids one comparison operation (1st check would always evaluate to true)
{
nSum += nRem % 10;
nRem /= 10;
} while (nRem > 9);
inputNum = nSum + nRem;
std::cout << "The current Sum is: " << inputNum << endl; // DEBUG - Please remove this
}
return inputNum;
}
As for the original code, the problem was the uninitialized sum variable, as already pointed out by other members - it even generates a compiler error.
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum = 0; // MAKE SURE YOU INITIALIZE THIS TO 0 BEFORE ADDING VALUES TO IT!
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
Initialize your variables before adding values to them, otherwise you could run into undefined behaviour. Also for the record, adding the cout line printed out something, but it wasn't the correct answer.
i tried to solve this problem with dfs and dynamic programming . then
i submit my code to my school grader but the answer is wrong .
am i implement something wrong with dfs .
what's wrong with my code.
PS.sorry for my bad english
The problem :
given a random number there's 2 different way you can do with this
number
1.divide it by 3 (it has to be divisible)
2.multiply it by 2
given n number find the original order before it was swapped
----EXAMPLE1---- INPUT : 6 4 8 6 3 12 9 OUTPUT : 9 3 6 12 4 8
----EXAMPLE2---- INPUT : 4 42 28 84 126 OUTPUT : 126 42 84 28
Here's my code
#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
int n ;
int input[51];
map<int,int> order ;
map<int,int> memo ;
bool valid(int a){
for(int i=0;i<n;i++){
if(input[i]==a)return 1 ;
}
return 0 ;
}
void dfs(int st){
memo[st]=1;
if(valid(st/3)){
if(memo[st/3]==0){
dfs(st/3);
order[st]+=order[st/3];
}
else order[st]+=order[st/3];
}
if(valid(st*2)){
if(memo[st*2]==0){
dfs(st*2);
order[st]+=order[st*2];
}
else order[st]+=order[st*2];
}
}
int main(){
cin >> n ;
for(int i=0;i<n;i++){
cin >> input[i];
memo[input[i]]=0;
order[input[i]]=1;
}
for(int i=0;i<n;i++){
if(memo[input[i]]==0)dfs(input[i]);
}
for(int i=n;i>=1;i--){
for(int k=0;k<n;k++){
if(order[input[k]]==i){
printf("%d ",input[k]);
break;
}
}
}
}
Information the OP should have told us in the first place:
my code gave the correct answer only 7 of 10 test case .i've already
asked my teacher he only told me to be careful with the recursion .
but i couldn't figure it out what's wrong with my recursion or
something else
An example that "fails":
Here's a failing case: Say you have the sequence 3 1 2 4. valid will
return true for 4 / 3 because it sees 1 in the sequence. –
Calculuswhiz
the better solution
#include<bits/stdc++.h>
using namespace std;
struct number{
long long int r , f3 , f2 ;
};
vector<number> ans ;
bool cmp(number a,number b){
if(a.f3!=b.f3)return a.f3>=b.f3;
if(a.f2!=b.f2)return a.f2<=b.f2;
return true ;
}
int main(){
int n ;cin>> n ;
long long int input ;
for(int i=0;i<n;i++){
cin >> input ;
long long int r = input ;
long long int f3 = 0, f2 = 0 ;
while(input%3==0){
f3++;
input/=3;
}
while(input%2==0){
f2++;
input/=2;
}
ans.push_back({r,f3,f2});
}
sort(ans.begin(),ans.end(),cmp);
for(auto i : ans){
cout << i.r << " " ;
}
}
The darkest place is under the lamp.
Look at the problem definition:
1.divide it by 3 (it has to be divisible)
Where do you test for the divisibility?
So, one error is here:
if(valid(st/3)){
This test should read:
if(st % 3 == 0 && valid(st/3)){
With this simple improvement, all three test cases pass.
A hint to improve (simplify) the solution
Numbers that are not divisible by 3 must come after those divisible.
Similarly, those not divisible by 9 must be coming after those that does.
Similarly for 27, 81,...
Now, if you divide your numbers into subsets of numbers of the form n = 3^k*m, where m % 3 != 0, then in each such a subset the only operation allowed by your algorithm is "multiply by 2". So it suffices to order them in ascending order.
The problem can be solved without dfs, nor is recurnece really necessary. Just order the numbers in a funny way: in descending order with respect to the number of times the number is divisible by 3, and then in ascending order. So, a task for you: challenge your teacher with a solution that, once the numbers are read in, does just one instruction std::sort (or qsort, as I see you write in C), then tests the validity of the solution, and prints it.
Moreover, I've just proved that if a solution exists, it is unique.
can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!
1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;
5 int main(){
6 int n, a , b , ma=0,mb=1000000001;
7 cin >> n ;
8 cin >> a;
9 for( n--; n ; --n ){
10 cin >> b;
11 if(abs(a-b) < abs(ma-mb))
12 ma=a , mb=b;
13 else
14 if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15 ma=a , mb=b;
16 a = b;
17 }
18 cout << ma << " " << mb;
19 return 0;
20 }
A for loop is simply another way to write a while loop. So this:
for( n--; n ; --n ){
...
}
is the same as this:
n--;
while(n) {
...
--n;
}
Which, in this specific case, is easier to read. First it decrements n, then does the loop, decrementing n again at the end of each loop, until that decrement causes n to evaluate to false by becoming 0.
This code smells a lot. If you give to n the value 10,it gives
9 (first time into loop, exectues n--)
every other iteration it executes --n till when n!=0 (which is the condition n
A for loop works the following way:
It runs for a certain number of times. We signify this with a condition. It has a start and an increment:
for (start ; condition ; increment )
{
// loop body
}
For loops and all loops are very useful when you want to perform repetitive tasks.
Lets say that you want to make a game and this game will have 3 rounds. Each one of those rounds can be implemented as an iteration of a for loop. It will look like this:
for(int round = 0; round < 3; ++round) {
// game round logic
}
In the above loop we start at 0. Once we reach 3, we would have already executed the for-loop 3 times. After each iteration of the for loop ++round gets executed, this increments the variable round by 1. We can increment it by a different value by doing: round+=2 or round*=2 etc.
This is my code for finding prime numbers between two integers. It compiles alright but giving a runtime error SIGXFSZ on codechef.
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n,m;
int t;
cin>>t;
while(t--)
{
cin>>m>>n;
for(long long j=m;j<=n;j++)
for(long long i=2;i<=sqrt(j);i++)
if(j%i==0)
break;
else cout<<j<<"\n";
cout<<"\n";
}
return 0;
}
Seems that you are wrong on logic.
According to my understanding, you are supposed to print the prime numbers between two numbers.
But your code has logical errors.
1) Code doesn't consider 2 and 3 as prime numbers.
Say, m = 1, n = 10. For j = 2, 3, the inner loop won't execute even for the single time. Hence, the output won't be shown to be user.
2) else cout<<j<<"\n"; statement is placed incorrectly as it will lead to prime numbers getting printed multiple times and some composite numbers also.
Example:
For j = 11, this code will print 11 twice (for i = 2, 3).
For j = 15, this code will print 15 once (for i = 2) though it is a composite number.
You've underexplained your problem and underwritten your code. Your program takes two separate inputs: first, the number of trials to perform; second, two numbers indicating the start and stop of an individual trial.
Your code logic is incorrect and incomplete. If you were to use braces consistently, this might be clear. The innermost loop needs to fail on non- prime but only it's failure to break signals a prime, so there can't be one unless the loop completes. The location where you declare a prime is incorrect. To properly deal with this situation requires some sort of flag variable or other fix to emulate labelled loops:
int main() {
int trials;
cin >> trials;
while (trials--)
{
long long start, stop;
cin >> start >> stop;
for (long long number = start; number <= stop; number++)
{
if (number < 2 || (number % 2 == 0 && number != 2))
{
continue;
}
bool prime = true;
for (long long odd = 3; odd * odd <= number; odd += 2)
{
if (number % odd == 0)
{
prime = false;
break;
}
}
if (prime)
{
cout << number << "\n";
}
}
}
return 0;
}
The code takes the approach that it's simplest to deal with even numbers and two as a special case and focus on looping over the odd numbers.
This is basically "exceeded file size", which means that the output file is having size larger than the allowed size.
Please do check the output file size of your program.
This question already has answers here:
Sorting std::strings with numbers in them?
(4 answers)
Closed 6 years ago.
I have problem solving this problem.
The task is simple at first line I enter how many examples I have.
On second line I need to enter how many numbers im going to read.
and then we enter all the numbers separate by space.
The task itselfs do , sorting the string array wtih numbers from smalles to the biggest one. After that if we have even numbers entered we print the middle number -1, if they are uneven we just print the middle number.
So far if I use the exact same code with long long it works perfectly , but it is limited only to 19 digit number and I want to expand the program so it can use bigger numbers.
Using that way the sort func , when I try to sort 16 elements from 160 to 10 , they all messed it start from 110 then in the midle is 160 and so one , which makes absolutly non sense, using 5 numbers or 8 works perfectly w/o any problem , using more numbers fails.
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
int examples;
cin >> examples;
for (size_t i = 0; i < examples; i++)
{
long long unsigned int n;
cin >> n;
string * numbers = new string[n];
for (size_t i = 0; i < n; i++)
{
cin >> numbers[i];
}
sort(numbers, numbers + n);
if (n % 2 == 0) {
cout << numbers[n / 2 - 1];
}
else
cout << numbers[n / 2];
}
system("pause");
return 0;
}
First, if you allocate memory with operator new, you must release it with operator delete[].
Second, when you sort strings instead of values, they are sorted just like strings would do, and here is where your problem lies. You see, 100 is alphabetically less than 2 or 20, that's why it would appear earlier.
Here's the output your program gives. Check this rule out, and you'll see that i'm right.
10 100 110 120 130 140 150 160 20 30 40 50 60 70 80 90
Third, using operator new is discouraged for pretty much anything. You have STL, and you seem to be using it extensively - why not vector?
Fourth, you don't check if anything we write into numbers[i] is actually a number. Think on that.
Fifth, for N being long enough(more than 2^sizeof(size_t)) your problem will NEVER stop due to integer overflow.
Sixth, you don't check for n == 0, and you will ultimately get memory access violation if you enter it.
A fast-right-off-the-bat fix for your problem:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main() {
int examples;
cin >> examples;
for (size_t i = 0; i < examples; i++)
{
size_t n;
cin >> n;
if (n <= 0)
break;
vector<string> numbers(n);
for (size_t i = 0; i < n; i++)
cin >> numbers[i];
//here we add a predicate for string checking,
//which evaluates the length of string
//before using the usual operator<.
sort(begin(numbers), end(numbers), [](const string& s1, const string& s2){
if (s1.length() < s2.length())
return true;
if (s2.length() < s1.length())
return false;
else
return (s1 < s2);
});
if (n % 2 == 0) {
cout << numbers[n / 2 - 1];
}
else
cout << numbers[n / 2];
}
system("pause");
return 0;
}
Still, it has a number of problems:
Checking if numbers[i] is actually a number
I'm not sure that
predicate I wrote doesn't have bugs - I'm just trying to give you
the idea of how it should work.