N = Input How much attempt (First Line).
s = Input How much value can be added (Second, fourth and sixth lines).
P = Input of numbers separated with space.
Example :
3 ( Input N )
2 ( s 1 )
2 3
3 ( s 2 )
1 2 3
1 ( s 3 )
12
Example :
Read #1: 5 (Output s1 = 2 + 3)
Read #2: 6 (Output s2 = 1+2+3)
Read #3: 12 (Output s3 = 12)
I've been searching and trying for very long but couldn't figure out such basic as how to cin based on given numbers, with spaces and add all values into a variable. For example:
#include <iostream>
using namespace std;
int main() {
int l, o[l], r, p[r], i;
cin >> l;
for(i = 0; i < l; i++) {
cin>>o[l];
r = o[l]; // for every o[0] to o[l]
}
while (cin>>o[l]) {
for (i = 0; i < l; i++){
cin>>p[o]; // for every o[0] to o[l]
// i.e o[l] = 1 then 2 values can be added (because it starts from zero)
// input 1 2
// o[1] = {1, 2}
int example += o[1];
cout<< "Read#2: " << example;
}
}
}
And it doesn't work. Then i found getline(), ignoring the s and just input anything that will finally be added to a number, turned out it is only usable for char string. I tried scanf, but I'm not sure how it works. So im wondering if it's all about s(values) × 1(column) matrix from a looping but sill not sure how to make it. Any easy solutions to this without additional libraries or something like that? Thanks in advance.
#include <iostream>
using namespace std;
int main() {
int t; //number of attempts
cin >> t;
while(t--) { // for t attempts
int n, s = 0; //number of values and initial sum
cin >> n;
while (n--) { //for n values
int k; //value to be added
cin >> k;
s += k; //add k to sum
}
cout << s << "\n"; //print the sum and a newline
}
return 0;
}
If you want to add more details, (i.e. print Read#n on the nth attempt), you can always use
for (int i = 1; i <= n; i++)
to replace while(t--) and at the end of the attempt just print
cout << "Read#" << i << ": " << s << "\n";
Related
I'm trying to find the highest value in a given list, but in an input list like this
7 385 -390 305 470 -145 255 30
my output is wrong, 385 instead of 470.
Could anyone please guide me towards my error!
Task description:
Read in an input value for variable numIn. Then, read numIn integers from input and output the largest of the integers read. End with a newline.
Ex: If the input is 2 345 -5, then the output is:
345
my code below
#include <iostream>
using namespace std;
int main() {
int numIn;
int high = 0;
cin >> numIn;
for (int i = 0; i < numIn; i++) {
cin >> numIn;
if (numIn > high) {
high = numIn;
}
}
cout << high << endl;
return 0;
}
First of all, your list has negative numbers. You can't set the default value of high to 0 since a list with all negative numbers won't work if you do this.
The error in your loop occurs because you overwrite numIn. Use a different variable for the number of input numbers.
cin >> numIn; // numIn is the number of input numbers
for (int i = 0; i < numIn; i++) {
cin >> numIn; // oops, numIn is now the first input number. it has been overwritten.
if (numIn > high) {
high = numIn;
}
}
A correct solution would look like this:
#include <iostream>
int main() {
int N; // assume that N >= 1. You could also replace this with numIn.
std::cin >> N;
int max;
std::cin >> max; // take in the first integer outside the loop
for (auto i = 1; i < N; i++) { // loop which runs N - 1 times
int E;
std::cin >> E;
max = std::max(max, E);
}
std::cout << max << '\n';
}
Without using std::max()
If you don't want to use std::max(), replace the line where you use it with a normal comparison (this is what std::max() does internally too)
if (E > max) { max = E; }
#include <iostream>
#include<ctime>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
int arr[10];
int a = pow(10, num);
int b = pow(10, (num - 1));
srand(static_cast<int>(time(NULL)));
do {
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
for (int m = 0; m < num; m++)
{
for (int j = 0; j < m; j++) {
if (m != j) {
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
cout << num2 << endl;
} while (!cont);
return 0;
}
I want to take a number from the user and produce such a random number.
For example, if the user entered 8, an 8-digit random number.This number must be unique, so each number must be different from each other,for example:
user enter 5
random number=11225(invalid so take new number)
random number =12345(valid so output)
To do this, I divided the number into its digits and threw it into the array and checked whether it was unique. The Program takes random numbers from the user and throws them into the array.It's all right until this part.But my function to check if this number is unique using the for loop does not work.
Because you need your digits to be unique, it's easier to guarantee the uniqueness up front and then mix it around. The problem-solving principle at play here is to start where you are the most constrained. For you, it's repeating digits, so we ensure that will never happen. It's a lot easier than verifying if we did or not.
This code example will print the unique number to the screen. If you need to actually store it in an int, then there's extra work to be done.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
int main() {
std::vector<int> digits(10);
std::iota(digits.begin(), digits.end(), 0);
std::shuffle(digits.begin(), digits.end(), std::mt19937(std::random_device{}()));
int x;
std::cout << "Number: ";
std::cin >> x;
for (auto it = digits.begin(); it != digits.begin() + x; ++it) {
std::cout << *it;
}
std::cout << '\n';
}
A few sample runs:
Number: 7
6253079
Number: 3
893
Number: 6
170352
The vector digits holds the digits 0-9, each only appearing once. I then shuffle them around. And based on the number that's input by the user, I then print the first x single digits.
The one downside to this code is that it's possible for 0 to be the first digit, and that may or may not fit in with your rules. If it doesn't, you'd be restricted to a 9-digit number, and the starting value in std::iota would be 1.
First I'm going to recommend you make better choices in naming your variables. You do this:
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
What are num and num2? Give them better names. Why are you cin >> str? I can't even see how you're using it later. But I presume that num is the number of digits you want.
It's also not at all clear what you're using a and b for. Now, I presume this next bit of code is an attempt to create a number. If you're going to blindly try and then when done, see if it's okay, why are you making this so complicated. Instead of this:
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
You can do this:
for(int index = 0; index < numberOfDesiredDigits; ++index) {
arr[index] = rand() % 10;
}
I'm not sure why you went for so much more complicated.
I think this is your code where you validate:
// So you iterate the entire array
for (int m = 0; m < num; m++)
{
// And then you check all the values less than the current spot.
for (int j = 0; j < m; j++) {
// This if not needed as j is always less than m.
if (m != j) {
// This if-else is flawed
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
You're trying to make sure you have no duplicates. You're setting cont == true if the first and second digit are different, and you're breaking as soon as you find a dup. I think you need to rethink that.
bool areAllUnique = true;
for (int m = 1; allAreUnique && m < num; m++) {
for (int j = 0; allAreUnique && j < m; ++j) {
allAreUnique = arr[m] != arr[j];
}
}
As soon as we encounter a duplicate, allAreUnique becomes false and we break out of both for-loops.
Then you can check it.
Note that I also start the first loop at 1 instead of 0. There's no reason to start the outer loop at 0, because then the inner loop becomes a no-op.
A better way is to keep a set of valid digits -- initialized with 1 to 10. Then grab a random number within the size of the set and grabbing the n'th digit from the set and remove it from the set. You'll get a valid result the first time.
So I am working on a very "basic" problem for my c++ class and have encountered some errors. The problem is this
An interesting problem in number theory is sometimes called the “necklace problem.” This problem begins with two single-digit numbers. The next number is obtained by adding the first two numbers together and saving only the ones-digit. This process is repeated until the “necklace” closes by returning to the original two numbers. For example, if the starting numbers are 1 and 8, twelve steps are required to close the “necklace”:
18976392134718
Write a program that asks the user for two starting numbers, and then displays the sequence and the number of steps taken. The program output should look similar to:
Enter first number: 1
Enter ssecond number: 8
18976392134718
Your numbers required 12 steps.
What I have done is this:
` #include <iostream>
using namespace std;
int necklace(){
int firstNumber, secondNumber, total = 0, counter = 10, sumOfTwo, tempOne, tempTwo, count;
// 2 single digit numbers
// add first two numbers and save only one digit
// process keeps going until original numbers are found
cout << "Enter the first number: \n";
cin >> firstNumber;
cout << "Enter the second number: \n";
cin >> secondNumber;
sumOfTwo = firstNumber + secondNumber;
while (sumOfTwo >= 10){
sumOfTwo /= 10;
}
int numbersArray[] = {firstNumber, secondNumber, sumOfTwo};
for(int i = 0; i <= 20; i++){
tempOne = numbersArray[i + 1];
tempTwo = numbersArray[i + 2];
sumOfTwo = tempOne + tempTwo;
while (sumOfTwo >= 10){
sumOfTwo %= 10;
}
numbersArray[i + 3] = sumOfTwo;
total++;
if(tempOne == firstNumber && tempTwo == secondNumber){
break;
}
}
for(int i = 0; i < sizeof(numbersArray); i++){
cout << numbersArray[i];
}
cout << endl << "It took " << total << " steps to finish. \n";
return total;
}
int main() {
necklace();
}
`
The problem I am getting is that it will print out all the numbers except the original 2, for example if I use the example with 1 and 8, it will print out 189763921347 and then crash, when it is supposed to print out 18976392134718 with the 1 and 8 at the end of it. Any suggestions? Thanks!
int numbersArray[] = {firstNumber, secondNumber, sumOfTwo};
with three elements on the right hand side makes it an array of size 3. Meaning with indexes 0, 1 and 2.
The use of higher indexes will result in Undefined Behaviour (UB).
On the other hand:
for(int i = 0; i <= 20; i++){
tempOne = numbersArray[i + 1];
tempTwo = numbersArray[i + 2];
[...]
numbersArray[i + 3] = sumOfTwo;
with i up to 20 (included) indexes this very same array from 0 to 23 for the last line!
Next:
for(int i = 0; i < sizeof(numbersArray); i++){
sizeof(numbersArray) returns the size in bytes of the array:
sizeof(numbersArray) = 3 * sizeof(int)
Higher than 3, the real size of the array.
But, if you intend to print the values but not store them, you don't need an array. You just need to "exchange" the values like:
one two // beginning of loop
___|
| __ new_digit
| |
v v
one two // end of loop
I'm trying to solve the following problem:
What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)
Example:
Input: 10, Output: 3. (10 = 3! + 2! + 2!)
Input: 25, Output: 2. (25 = 4! + 1!)
My code:
#include<bits/stdc++.h>
using namespace std;
int a;
int rec(int vet){
int count = 0;
a = a - vet;
if(a >= vet){
count++;
rec(vet);
}
count++;
return count;
}
int main(){
int vet[8] = {1}, count = 0;
cin >> a;
for(int i = 2; i <= 8; i++){
vet[i-1] = vet[i-2]*i;
}
for(int i = 7; i >= 0; i--){
if(a < vet[i]){
continue;
}
count += rec(vet[i]);
}
cout << count << endl;
}
My logic:
1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;
2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.
This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.
Can you find where am I wrong? Or if my solution is not good and I should try another approach.
Thanks for the help!
The problem is easily solved by a recursive approach.
Here is checked code:
#include <iostream>
using namespace std;
int factorial(int n) {
return n<=1 ? 1 : n * factorial(n-1);
}
int MinFact(int number)
{
static int num_of_facts;
int a = 1;
if (number)
{
while(factorial(a+1)<=number)a++;
cout << a << "!" << endl;
num_of_facts++;
MinFact((number-factorial(a)));
}
return num_of_facts;
}
int main()
{
int num;
cout << "Enter number" << endl;
cin >> num;
num = MinFact(num);
cout << "Number of factorials: " << num;
return 0;
}
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.
A simple solution would be to replace the rec function as follows
int rec(int vec) {
int count = a / vec;
a = a % vec;
return count;
}
Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.
I'm trying to enter integers for a and b and then print those integers put together. For example, entering 1 2 3 4 for a and 4 3 2 1 for b would yield: 1 2 3 4 4 3 2 1. I don't understand why my program isn't printing this. Whenever I enter -1, nothing happens. Am I doing the process wrong while the program is running? Help is appreciated.
#include <iostream>
#include <vector>
using namespace std;
vector<int> append(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> c(n + m);
int i;
for (i = 0; i < n; i++)
c[i] = a[i];
for (i = 0; i < m; i++)
c[n + i] = b[i];
return c;
}
main()
{
vector<int>a, b, c;
int temp;
cin >> temp;
while (temp != -1) {
a.push_back(temp);
cin >> temp;
}
cin >> temp;
while (!cin.eof()) {
b.push_back(temp);
cin >> temp;
}
c = append(a, b);
for (int i = 0; i < c.size(); i++)
cout << c[i] << " ";
cout << endl;
}
You have two loops, one to input the vector a and another to input b.
Hitting -1 once would terminate only the first loop. The second one is terminated by an eof which you still haven't entered. So either enter an eof (specific to your system) or have the second loop terminate at -1 (in which case you'll need to enter -1 once more).
You say
Whenever I enter -1, nothing happens.
That's because you reach the second cin >> temp statement at that time (just before while.eof() loop). That's when you start inputting values for b vector. You end that loop by entering EOF character in the stream (CTRL+Z on windows, CTRL+D on linux).