Look at this code, In my VS code or some online compilers it gives favorable output, but when I'm submitting this on HackerRank or this online compiler I'm getting wrong output but only when I provide input as: 1 1 1 100...and I'm not able to spot the Error?..I'm providing question for reference.
/*There will be two arrays of integers. Determine all integers that satisfy
the following two conditions:
The elements of the first array are all factors of the integer being
considered
The integer being considered is a factor of all elements of the second array
These numbers are referred to as being between the two arrays. Determine how
many such numbers exist.
*/
#include <iostream>
int main()
{
int count1, count2;
int num1[20], num2[20];
std::cin >> count1 >> count2;
for (int i = 0; i < count1; i++)
{
std::cin >> num1[i];
}
for (int i = 0; i < count2; i++)
{
std::cin >> num2[i];
}
int occurence_firstarray = 0, occurence_secondarray = 0, totalvalid_occurence = 0;
for (int i = num1[count1 - 1]; i < num2[1]; i++)
{
occurence_firstarray = 0;
occurence_secondarray = 0;
for (int j = 0; j < count1; j++)
{
if (i % num1[j] == 0)
{
occurence_firstarray++;
}
}
if (occurence_firstarray == count1)
{
for (int p = 0; p < count2; p++)
{
if (num2[p] % i == 0)
{
occurence_secondarray++;
}
}
}
if (occurence_secondarray == count2)
{
totalvalid_occurence++;
}
}
std::cout << totalvalid_occurence;
return (0);
}
Considering your inputs: 1 1 1 100,
What are you doing in this code is You are pointing on index beyond your second array's size limit i < num2[1], this is why you are getting wrong outputs.
Do some changes as, i <= num2[0];
Related
I have an assignment to make a program that should convert a number from it's integer value to a binary value. For some reason my array is always filled with zeroes and won't add "1"'s from my if statements. I know there are probably solutions to this assignment on internet but I would like to understand what is problem with my code. Any help is appreciated.
Here is what I tried:
#include <iostream>
/*Write a code that will enable input of one real number in order to write out it's binary equivalent.*/
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
while (number > 0) {
int i = 0;
if ((number / 10) % 2 == 0) {
binaryNumber[i] = 0;
}
if ((number / 10) % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 10;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
You need to remove number/10 in both the if statements. Instead, just use number. you need the last digit every time to get the ith bit.
Moreover, you need to just half the number in every iteration rather than doing it /10.
// Updated Code
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
int i = 0;
while (number > 0) {
if (number % 2 == 0) {
binaryNumber[i] = 0;
}
if (number % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 2;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
The first thing is the variable 'i' in the while loop. Consider it more precisely: every time you iterate over it, 'i' is recreated again and assigned the value of zero. It's the basics of the language itself.
The most relevant mistake is logic of your program. Each iteration we must take the remainder of division by 2, and then divide our number by 2.
The correct code is:
#include <iostream>
int main()
{
int x = 8;
bool repr[32]{};
int p = 0;
while(x)
{
repr[p] = x % 2;
++p;
x /= 2;
}
for(int i = 31; i >= 0; --i)
std::cout << repr[i];
return 0;
}
... is always filled with zeroes ... I would like to understand what is problem with my code
int i = 0; must be before the while, having it inside you only set the index 0 of the array in your loop because i always values 0.
But there are several other problems in your code :
using int binaryNumber[32] you suppose your int are on 32bits. Do not use 32 but sizeof(int)*CHAR_BIT, and the same for your last loop in case you want to also write 0 on the left of the first 1
you look at the value of (number / 10) % 2, you must look at the value of number % 2
it is useless to do the test then its reverse, just use else, or better remove the two ifs and just do binaryNumber[i] = number & 1;
number = number / 10; is the right way when you want to produce the value in decimal, in binary you have to divide by 2
in for (int i = 31; i >= 0; i--) { except for numbers needing 32 bits you will write useless 0 on the left, why not using the value of i from the while ?
There are some logical errors in your code.
You have taken (number/10) % 2, instead, you have to take (number %2 ) as you want the remainder.
Instead of taking i = 31, you should use this logic so you can print the following binary in reverse order:
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
Here is the code to convert an integer to its binary equivalent:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to convert integer to binary
void DecBinary(int n)
{
// Array to store binary number
int BinaryNumb[32];
int i = 0;
while (n > 0)
{
// Storing remainder in array
BinaryNumb[i] = n % 2;
n = n / 2;
i++;
}
// Printing array in reverse order
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
}
// Main Program
int main()
{
int testcase;
//Loop is optional
for(int i = 0; i < testcase; i++)
{
cin >> n;
DecToBinary(n);
}
return 0;
}
In the following code, I am having trouble comparing specific letters two given strings.
#include <bits/stdc++.h>
using namespace std;
int main() {
int m, n;
cin >> m >> n;
cin.ignore();
string phrases[m];
string records[n];
for (int i = 0; i < m; i++) {
getline(cin, phrases[i]);
}
for (int i = 0; i < n; i++) {
getline(cin, records[i]);
}
int lowBound;
sort(phrases, phrases + m);
int ans = 0;
bool stillIs;
for (int i = 0; i < n; i++) {
lowBound = lower_bound(phrases, phrases + m, records[i]) - phrases;
if (lowBound == m) {
continue;
}
stillIs = true;
for (int j = 0; j < records[i].length(); i++) {
if (records[i][j] == phrases[lowBound][j]) {
stillIs = false;
}
}
if (stillIs) {
ans++;
}
}
cout << ans;
return 0;
}
On line 33, if (records[i][j] == phrases[lowBound][j]), it is not giving me an error, but if I run it with this line, nothing happens, but when I comment the if statement out, it works properly, but obviously not giving me the correct answer. Is there any way I can compare these two strings (the second one is larger in size than the first one) to find whether the first one is the start of the second one?
Thanks!
You are incrementing i instead of j in the loop at line 32
You have your test backwards in line 33 - you want to set stillIs = false if the characters don't match, (i.e., !=)
I haven't fully read your code, but those two problems jumped out at me, so see if that sorts it out
Homework: I'm just stumped as hell. I have algorithms set up, but I have no idea how to code this
Just to be clear you do not need arrays or to pass variables by reference.
The purpose of the project is to take a problem apart and using Top-Down_Design or scratch pad method develop the algorithm.
Problem:
Examine the numbers from 2 to 10000. Output the number if it is a Dual_Prime.
I will call a DualPrime a number that is the product of two primes. Ad where the two primes are not equal . So 9 is not a dual prime. 15 is ( 3 * 5 ) .
The output has 10 numbers on each line.
My Algorithm set-up
Step 1: find prime numbers.:
bool Prime_Number(int number)
{
for (int i = 2; i <= sqrt(number); i++)
{
if (number % 1 == 0)
return false;
}
return true;
}
Step 2: store prime numbers in a array
Step 3: Multiply each array to each other
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int j = 0; j < Size- 1; j++)
{
Dual_Prime[] = Arr[j] * Arr[j + 1]
}
}
Step 4: Bubble sort
void Bubble_Sort(int Array[], int Size) // Sends largest number to the right
{
for (int i = Size - 1; i > 0; i--)
for (int j = 0; j < i; j++)
if (Array[j] > Array[j + 1])
{
int Temp = Array[j + 1];
Array[j + 1] = Array[j];
Array[j] = Temp;
}
}
Step 5: Display New Array by rows of 10
void Print_Array(int Array[], int Size)
{
for (int i = 0; i < Size; i++)
{
cout << Dual_Prime[i] << (((j % 10) == 9) ? '\n' : '\t');
}
cout << endl;
}
I haven't learned dynamic arrays yet,
Although dynamic arrays and the sieve of Eratosthenes are more preferable, I tried to write minimally fixed version of your code.
First, we define following global variables which are used in your original implementation of Multiply_Prime_Numbers.
(Please check this post.)
constexpr int DP_Size_Max = 10000;
int DP_Size = 0;
int Dual_Prime[DP_Size_Max];
Next we fix Prime_Number as follows.
The condition number%1==0 in the original code is not appropriate:
bool Prime_Number(int number)
{
if(number<=1){
return false;
}
for (int i = 2; i*i <= number; i++)
{
if (number % i == 0)
return false;
}
return true;
}
In addition, Multiply_Prime_Numbers should be implemented by double for-loops as follows:
void Multiply_Prime_Numbers(int Array[], int Size)
{
for (int i = 0; i < Size; ++i)
{
for (int j = i+1; j < Size; ++j)
{
Dual_Prime[DP_Size] = Array[i]*Array[j];
if(Dual_Prime[DP_Size] >= DP_Size_Max){
return;
}
++DP_Size;
}
}
}
Then these functions work as follows.
Here's a DEMO of this minimally fixed version.
int main()
{
int prime_numbers[DP_Size_Max];
int size = 0;
for(int j=2; j<DP_Size_Max; ++j)
{
if(Prime_Number(j)){
prime_numbers[size]=j;
++size;
}
}
Multiply_Prime_Numbers(prime_numbers, size);
Bubble_Sort(Dual_Prime, DP_Size);
for(int i=0; i<DP_Size;++i){
std::cout << Dual_Prime[i] << (((i % 10) == 9) ? '\n' : '\t');;
}
std::cout << std::endl;
return 0;
}
The Sieve of Eratosthenes is a known algorithm which speeds up the search of all the primes up to a certain number.
The OP can use it to implement the first steps of their implementation, but they can also adapt it to avoid the sorting step.
Given the list of all primes (up to half the maximum number to examine):
Create an array of bool as big as the range of numbers to be examined.
Multiply each distinct couple of primes, using two nested loops.
If the product is less than 10000 (the maximum) set the corrisponding element of the array to true. Otherwise break out the inner loop.
Once finished, traverse the array and if the value is true, print the corresponding index.
Here there's a proof of concept (implemented without the OP's assignment restrictions).
// Ex10_TwoPrimes.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Homework_Header(string Title);
void Do_Exercise();
void Sieve_Of_Eratosthenes(int n);
void Generate_Semi_Prime();
bool Semi_Prime(int candidate);
bool prime[5000 + 1];
int main()
{
Do_Exercise();
cin.get();
return 0;
}
void Do_Exercise()
{
int n = 5000;
Sieve_Of_Eratosthenes(n);
cout << endl;
Generate_Semi_Prime();
}
void Sieve_Of_Eratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
memset(prime, true, sizeof(prime));
for (int p = 2; p*p <= n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
bool Semi_Prime(int candidate)
{
for (int index = 2; index <= candidate / 2; index++)
{
if (prime[index])
{
if (candidate % index == 0)
{
int q = candidate / index;
if (prime[q] && q != index)
return true;
}
}
}
return false;
}
void Generate_Semi_Prime()
{
for (int i = 2; i <= 10000; i++)
if (Semi_Prime(i)) cout << i << "\t";
}
I am working on codechef practice problem in which I have to find longest common substring. ( Its practice problem so don't down vote )
Following wiki and some resources online I got the algorithm
https://en.wikipedia.org/wiki/Longest_common_substring_problem
After understanding I wrote the algorithm in c++ , but its compiling but not running successfully . Throwing error while assigning value to vector matrix .
An invalid parameter was passed to a function that considers invalid parameters fatal.
1) Whats wrong with my LCSubstring function
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int max(int a, int b) {
return a > b ? a : b;
}
int LCSubString(string str1 , string str2) {
// create 2d matrix
vector<vector<int>> matrix;
int maxlength = 0;
for (int i = 0; i <= str1.length(); i++) {
for (int j = 0; j <= str2.length(); j++) {
if (i == 0 && j == 0) {
matrix[i][j] = 0;
continue;
}
if (str1[i - 1] == str2[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
maxlength = max(maxlength, matrix[i][j]);
}
else {
matrix[i][j] = 0;
}
}
}
return maxlength;
}
int main()
{
int t;
int count = 0;
string str;
int len;
cin >> t;
while (t--) {
cin>> str;
len = LCSubString(str, "chef");
if (len >= 2) {
count++;
}
}
cout << count << endl;
return 0;
}
You did not properly initialize std::vector<std::vector<int>> matrix. They do not automatically resize when you access them with [], you need to set the proper size beforehand, like this:
vector<vector<int>> matrix(str.length()+1);
for (int i = 0; i <= str1.length(); ++i)
matrix[i] = vector<int>(str2.length()+1, 0);
Additionally, you are not properly checking for i == 0 or j == 0. If only one of them is zero then the first if in your loop won't hit and you subsequently try to read string[-1]. I don't know whether it would be correct for your algorithm, but try using logical or (||) instead of and (&&).
Currently studying software engineering at college (first year) and made a program where the user enters how many entries there will be and then they input the times for each entry and it is sorted in descending order.
The problem I am having is when I enter a large number for the first input it doesn't sort correctly but the rest do. It would be great if someone could help me out with this and sorry for the noob question:P
The entire code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int TotalSize = 0;
void getSpeed(int *CalculationTime, int NoOfCalculations)
{
for (int i = 0; i < NoOfCalculations; i++)
{
cout << "Please enter the speed of calculation " << i + 1 << "(Ms): "; cin >> CalculationTime[i];
}
}
void sort_speeds(int *CalculationTime, int NoOfCalculations)
{
// Sorting speeds in decending order
bool swapped = true;
int i, j = 0;
int temp;
while (swapped)
{
swapped = false;
j++;
for (i = 1; i < NoOfCalculations - j; i++)
{
if (CalculationTime[i] > CalculationTime[i + 1])
{
temp = CalculationTime[i];
CalculationTime[i] = CalculationTime[i + 1];
CalculationTime[i + 1] = temp;
swapped = true;
}
}
}
// Output times decending order
for (int i = 0; i < NoOfCalculations; i++)
{
cout << CalculationTime[i] << "\n";
}
}
int main()
{
// Declaring & Initializing variables
int NoOfCalculations = 0;
int *CalculationTime = new int[NoOfCalculations];
// Getting user input
cout << "How many calculations are there? "; cin >> NoOfCalculations;
getSpeed(CalculationTime, NoOfCalculations);
// Sorting and displaying times
sort_speeds(CalculationTime, NoOfCalculations);
system("pause");
return 0;
}
You've never compare first element of your array with anything - for (i = 1; i < NoOfCalculations - j; i++) should be for (i = 0; i < NoOfCalculations - j; i++)
The issue is for (i = 1; i < NoOfCalculations - j; i++) You are starting at position 1, start at position 0 and it fixes the problem. for (i = 0; i < NoOfCalculations - j; i++)
// Declaring & Initializing variables
int NoOfCalculations = 0;
int *CalculationTime = new int[NoOfCalculations];
// Getting user input
cout << "How many calculations are there? "; cin >> NoOfCalculations;
Bzzzt. You allocate a zero-element array, and then don't reallocate it. I bet if you entered a large enough number for your number of calculations, your program would crash.
Really, you want to be using std::vector, an extremely useful datastructure, the use of which is a bit outside of the scope of this answer. Basically, you can do stuff like this:
std::vector<int> getSpeeds(int NoOfCalculations)
{
std::vector<int> speeds;
for (int i = 0; i < NoOfCalculations; i++)
{
int speed;
std::cout << "Please enter the speed of calculation " << i + 1 << "(Ms): ";
std::cin >> speed;
speeds.push_back(speed);
}
return speeds;
}
You can use the returned vector almost exactly as if it were an array:
std::vector<int> speeds = getSpeeds(10);;
if (CalculationTime[3] > CalculationTime[4])
// do something
Often, in a C++ application, the explicit use of pointers is a sign that you're not using the standard library, and as a result making life much, much harder for yourself.
Oh, and also:
for (i = 1; i < NoOfCalculations - j; i++)
You never look at NoOfCalculations[0] or NoOfCalculations[i - 1], so you never touch the first element.
while (swapped)
{
swapped = false;
j++;
for (i = 0; i < NoOfCalculations - j; i++) //try and start i from 0. I think you are missing the first element to check
{
if (CalculationTime[i] > CalculationTime[i + 1])
{
temp = CalculationTime[i];
CalculationTime[i] = CalculationTime[i + 1];
CalculationTime[i + 1] = temp;
swapped = true;
}
}
}