The task of displaying numbers - c++

Can't complete the task and need your help. With single digits all OK, but when i trying numbers like 9865, output is wrong.
Task:
Input:
The first line contains an integer 𝑛 (0 ≀ 𝑛 ≀ 1e6). The second line contains nine separated by a space
integers π‘Ž1, π‘Ž2,…, π‘Ž9(1 ≀ π‘Žπ‘– ≀ 1e5) - the value in gold of each digit (from 1 to 9, respectively).
Output:
Print the maximum number for which the player has enough gold. The value of the number is equal to the sum of the values
each digit included in it. If the player does not have enough gold for any number, then output βˆ’1
EXAMPLE:
Input:
n = 2
a[9] = {1 2 3 4 4 4 4 4 4}
Output:
11
Note:
In the example, two units of gold may only be enough for one digit 2 or two digits 1, so the maximum number that can be applied is 11.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
const int MAX = 9;
int main()
{
int a[MAX]; // array
int b[MAX];
unsigned int n; // gold
cin >> n;
for (int i = 0; i < MAX; i++)
{
cin >> a[i];
}
for (int i = 0; i < MAX; i++)
{
int count = n / a[i];
int post = n % a[i];
if (count == 0)
{
b[i] = 0;
}
else
{
for (int k = 0; k < count; k++)
{
if (post == 0)
{
string prom = to_string(a[i]); // int to string
if (count > 1)
{
prom += to_string(a[i]);
}
b[i] = atoi(prom.c_str()); // string to int
}
else
{
string prom = to_string(a[i]); // int to string
if (count > 1)
{
prom += to_string(a[i]) + to_string(post);
}
b[i] = atoi(prom.c_str()); // string to int
}
}
}
}
int maxnum = 0;
for (int i = 0; i < MAX; i++)
{
if (b[i] > maxnum)
{
maxnum = b[i];
}
}
cout << maxnum;
return 0;
}

Related

Listing down permutations of digit in integer form in C++ using 2 for loops, by only switching 2 digits

I need to make a code to switch 2 digits in a number and make it into a new integer
For example
12-->21
123 becomes
213(1,2 switch)
312(1,3 switch)
132 (2,3 switch)
for up to 8 digits of numbers
this is what I came up so far
#include <iostream>
#include <iomanip>
using namespace std;
int digitcount(int n) {
int count=0;
if (n == 0)
return 1;
while (n != 0) {
n = n / 10;
count++;
}
return count;
}
int pow(int num,int n) {
int x = 1;
if (n == 0) {
return 1;
}
for (int i = 0; i < n; i++) {
x = x * num;
}
return x;
}
int a[8];
int main() {
int input;
int newnum = 0;
cout << "Input an integer: ";
cin >> input;
int b = input;
int digit = digitcount(input);
for (int i = digit-1; i>=0; i--) {
a[i] = b % 10;
b = b / 10;
}
for (int i = 0; i < digit - 1; i++) {
newnum = 0;
for (int j = i+1; j < digit; j++) {
if (a[j] == a[i]) {
continue;
}
newnum = a[i] * pow(10, digit - j - 1) + a[i] * pow(10, digit);
}
}
}

Prime Number finding algorithm returns weird values

I am beginning to learn c++, and was working through the Project Euler challenges, and #7 asks you to find all prime numbers within a given range. After online research i decided to try using Sieve of Erastothenes, however with the code i have set up, i currently get weird values such as )2, 0) when i ask for 2 primes, and (2, 4, 5, 5) when i input 5.
#include <iostream>
#include <vector>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
int main(){
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
//creates a vector to store all values, that will eventually be whittled down to primes
vector<int> primes = {2};
//adds all numbers between 2 and chosen end point to the vector
for (int i = 3; i <= end_point; i++){
primes.push_back(i);
}
for (int i = 0; i < end_point; i++){
//starts at the first value (always 2), and feeds it into the next for loop
//once the next loop is done, it moves on to the next value in the loop and feeds that in
primes[i];
//looks at values in the vector, starting with the next value in the vector
for (unsigned int j = i+1; j < primes.size(); j++){
//checks if the value at [j] is divisible by the value at [i]
//if it is, this deletes it from the vecotr
//if not, it moves on to the next value in the vector
if(primes[j] % primes[i] == 0){
primes.erase (primes.begin() + (j-1));
}
else{}
}
//prints out all of the primes in the specified range
cout << "Primes are: ";
for (unsigned int k = 0; k <= primes.size(); k++){
cout << primes[k] << ", ";
}
}
}
You shouldn't remove element from array when you traverse it. You can try it by marking.
example:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main() {
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
//creates a vector to store all values, that will eventually be whittled down to primes
vector<int> primes = { 2 };
//adds all numbers between 2 and chosen end point to the vector
for (int i = 3; i <= end_point; i++) {
primes.push_back(i);
}
for (int i = 0; i < end_point; i++) {
//starts at the first value (always 2), and feeds it into the next for loop
//once the next loop is done, it moves on to the next value in the loop and feeds that in
int val = primes[i];
// to ensure the value is not zero
if (val == 0)
continue;
//looks at values in the vector, starting with the next value in the vector
for (unsigned int j = i + 1; j < primes.size(); j++) {
//checks if the value at [j] is divisible by the value at [i]
//if it is, this deletes it from the vecotr
//if not, it moves on to the next value in the vector
if (primes[j] > 0 && primes[j] % val == 0) {
// set the value zero to element of array.
primes[j] = 0;
}
}
//prints out all of the primes in the specified range
cout << "Primes are: ";
for (unsigned int k = 0; k <= primes.size(); k++) {
if (primes[k] > 0) // output the value which greater then zero.
cout << primes[k] << ", ";
}
}
return 0;
}
You delete wrong element. This is right:
primes.erase(primes.begin() + j);
Your last loop in wrong place. Take it out of previous 'for loop'. And you go after last element. Should be:
k < primes.size();
not
k <= primes.size();
=== Now it works properly ===
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main() {
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
vector<int> primes = { 2 };
for (int i = 3; i <= end_point; i++) {
primes.push_back(i);
}
for (int i = 0; i < end_point; i++) {
for (unsigned int j = i + 1; j < primes.size(); j++) {
if (primes[j] % primes[i] == 0) {
primes.erase(primes.begin() + j);
}
else {}
}
}
cout << "Primes are: ";
for (unsigned int k = 0; k < primes.size(); k++) {
cout << primes[k] << ", ";
}
return 0;
}
you can check prime from 2 to the sqrt of that number. this will omit duplicates and extra checks.
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
vector<int> getPrimes(int start, int end){
if( start <0 || end < 0 || end < start ){
return {};
}
int max = 0;
bool isPrime = true;
vector<int> prims = {};
for( int i = start ; i <= end ; i++ ){
max = sqrt(i);
isPrime = true;
for(int j = 2 ; j <= max ; j++ ){
if( i % j == 0 ){
isPrime = false;
break;
}
}
if(isPrime){
prims.push_back(i);
}
}
return prims;
}
int main()
{
vector<int> prims = getPrimes(0,100);
for(int n : prims) {
cout << n << '\n';
}
return 0;
}
Sqrt Reason:
imagine you want to find out that 17 is a prime number or not. the simplest way is to loop from 0 to 17 to check its multiples. but it doesn't needed to do that. the sqrt of 17 is almost 4. so you check the multiples until the number 4. the next number is 5. from 5 to 17, all the multiples that their results is smaller that 17 is from 4 to 0. because 5 * 5 is 25 . even 5 * 4 is 20. so all multiples going to be repetitious.
now you can just check multiples from 2 to square root of that number to find out the number is a prime number or not

Output not correct for my C++ program

So, I have the following problem:
From the file tabl.in a number n will be read (n<=50).
After that a square array with n rows and n columns will be read; all the numbers in the array will be composed by a maximum of 2 digits each.
Shown in the file tabl.out, the modulo between the sum of numbers found on the second diagonal of the array and 10, if the sum is palindrome (true=1, false=0), and the arithmetic mean of elements situated below of the main diagonal.
Will be writing functions for:
reading the array
calculation of the operation sum of secondary diagonal%10
checking if the previous result it is palindrome
calculation of the arithmetic mean below main diagonal
Example:
tabl.in:
4
5 8 2 12
1 0 3 16
1 2 1 11
5 7 2 19
tabl.out:
2 1 3
where
(12+3+2+5)%10 = 22%10 = 2
22 is palindrome = 1
1+2+2+1+7+5 = 18, 18/6=3
My code so far is:
#include <fstream>
using namespace std;
ifstream fin("tabl.in");
ofstream fout("tabl.out");
void readn(int Arr[][51], int n) {
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
fin >> Arr[i][j];
}
int sumsec(int Arr[][51], int n) {
int s = 0;
float r;
for (int i = 1; i <= n; i++)
s = s + Arr[i][n - i + 1];
r = s % 10;
return r;
}
void pald(int Arr[][51], int n) {
int s = 0, pal = 0;
for (int i = 1; i < n; i++)
s = s + Arr[i][n - i + 1];
while (s != 0) {
pal = pal * 10 + s % 10;
s = s / 10;
}
if (pal == s)
fout << "1 ";
else
fout << "0 ";
}
int ambmd(int Arr[][51], int n) {
int s = 0, k;
float ame;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i - 1; j++) {
s = s + Arr[i][j];
k++;
}
}
ame = s / k;
return ame;
}
int main() {
int Arr[51][51], n;
float r, ame;
fin >> n;
readn(Arr, n);
r = sumsec(Arr, n);
fout << r << " ";
pald(Arr, n);
ame = ambmd(Arr, n);
fout << ame;
}
But I have an issue with the palindrome() function: my output file will have 2 0 3 written to it for the given array from the example, instead of 2 1 3. What am I doing wrong?
Your pald function would work, if you compute s the same way as you do in sumsec and if s would still contain the sum, after you compute pal.
In your case, while (s != 0) {...}, followed by if (pal == s) {...} could be re-written as if (pal == 0), which is clearly not the intended solution. Just save your sum before computing pal, then compare with the saved sum.
Also, change your loop condition for computing s to for (int i = 1; i <= n; i++).
int s = 0, pal = 0, sum = 0;
for (int i = 1; i <= n; i++)
s = s + Arr[i][n - i + 1];
sum = s;
while (s != 0) {
pal = pal * 10 + s % 10;
s = s / 10;
}
if (pal == sum)
fout << "1 ";
else
fout << "0 ";
You should also consider the various comments for code improvements, like not re-computing the sum in the pald function.

C++ Sub sequence Exercise

I was assigned a "project" where I should create a C++ program to find the largest possible sum of two sub sequences. The user inputs N (array length), K (length of each sub sequence) and N numbers representing the array. The two sub sequences can touch but can't override each other e.g. 1 5 20 20 20 15 10 1 1 1 should output 90 ((5+20+20)+(20+15_10)) and not 115 ((20+20+20)+(20+20+15)).
My code until now is:
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int N, K, MaxN;
cin >> N;
cin >> K;
int Pi[N];
MaxN = N - K + 1;
int Word[MaxN];
int MaxSum;
for(int nn=0; nn<N; nn++) {
cin >> Pi[nn];
}
for(int y=0;y<MaxN;y++) {
Word[y] = 0;
}
for(int j=0; j<MaxN; j++) {
for(int l=0; l<K; l++) {
Word[j] = Word[j] + Pi[j+l];
}
}
sort(Word, Word + MaxN);
MaxSum = Word[MaxN-2] + Word[MaxN-1];
cout << MaxSum;
return 0;
}
Which is correct only in the case where the 2 sub sequences don't interfere with each other e.g. in an array such as 2 4 15 12 10 1 1 20 4 10 which outputs 71.
Thank you all in advance.
This is solution:
precalculate prefixes and suffixes
iterate end of the first subarray
iterate begin of the second subarray, but start from the end of first sub. ar. + 1
we have sum of numbers on interval from 0 to *end* = prefix[end], but we are interested only in interval [end - k, k], so simply subtract prefix[end] - prefix[end - k - 1]
[0 .. end-k-1, end-k .. end]
The same approach for the second subarray: sum2 = suffix[begin] - suffix[begin + i + 1]
then compare with the previous answer
So we just brute-force all possible sub-arrays which not intersect and find the max their sum
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int N,K,MaxN;
cin >> N;
cin >> K;
int Pi[N];
MaxN=N-K+1;
int Word[MaxN];
int MaxSum;
for(int nn=0;nn<N;nn++){
cin >> Pi[nn];
}
int prefix[N];
int sufix[N];
for (int i = 0; i < N; i++) {
prefix[i] = sufix[i] = 0;
}
for (int i = 0; i < N; i++) {
if (i == 0)
prefix[i] = Pi[i];
else
prefix[i] = Pi[i] + prefix[i - 1];
}
for (int i = N - 1; i >= 0; i--) {
if (i == N - 1)
sufix[i] = Pi[i];
else
sufix[i] = Pi[i] + sufix[i + 1];
}
int ans = 0;
for (int i = K - 1; i < MaxN; i++) {
for (int j = i + 1; j < MaxN; j++) {
int x = prefix[i] - (i - K >= 0 ? prefix[i - K] : 0);
int y = sufix[j] - (j + K < N ? sufix[j + K] : 0);
ans = max(ans, x + y);
}
}
cout << ans;
return 0;
}

C++: Counting zeros at the end optimization

I am trying to solve standard problem of calculating 0s at the end of factorial of any natural number. My code works fine but online judge gives "Time Limit Exceeded" error. Decided to ask here about how I can optimize my code.
#include <iostream>
using namespace std;
int count (int n)
{
int result = 0;
for (unsigned int i = 5; i <= n; i += 5)
{
int temp = i;
while (!(temp % 5))
{
++result;
temp /= 5;
}
}
return result;
}
int main()
{
int N;
cin >> N;
cin.get();
for (unsigned int i = 0; i < N; ++i)
{
int n;
cin >> n;
cin.get();
cout << count (n) << endl;
}
return 0;
}
Thanks in advance.
Try this:
int count (int n)
{
int result = 0;
for (unsigned int i = 5; i <= n; i *= 5)
result += n / i;
return result;
}
In 1*2*..*N, there are N/5 factors, which are divisable by 5. N/25 of those are also divisable by 25, ...
You haven't to check every number divisible by 5. Instead you can count 5's with simple series:
count = n div 5 + n div 25 + n div 125...