Logic behind this sequence is built but a problem is occurring? - c++

I have to print 8 terms of the sequence as
1, 2, 4, 8, 16, 22, 26, 38, ....
I have completed my logic till 16 that every new term is the previous term multiplied by 2. And after 16 the logic is that we divide that part into two as
26 = 22 + (2 * 2)
Till now what I have done is
int x = 1, num, num1, n = 1;
while (n <= 10)
{
while (n <= 4)
{
if (n == 1)
{
cout << x << ", ";
}
num = x % 10;
num1 = num % 10;
x = x * 2;
cout << x << ", ";
n++;
}
if (x == 16)
{
num = x % 10;
num1 = num % 10;
x = x + (num * num1) - 30;
cout << x << ", ";
}
else
{
num = x % 10;
num1 = num % 10;
x = x + (num * num1);
cout << x << ", ";
}
n++;
}

Apparently we just add the product of all digits to current number. That works fine for 1, 2, 4, 8 as well (e. g. 4 = 2 + (2)), so no need to have any special handling. However, apparently we need to ignore zeros, otherwise we wouldn't change after 102 any more...
So we can simplify the altorithm quite a bit:
unsigned int number = 1; // start value
std::cout << number; // OK, would require special handling for n == 0...
while(n--) // you could ask the user to input n or just set it to 10
// (I consider this variant a bit more elegant)
{
unsigned int product = 1;
unsigned int tmp = number;
// now iterate as long as you have more digits!
while(tmp)
{
unsigned int modulo = tmp % 10;
tmp /= 10;
// neat little trick: if modulo != 0, comparison is false, which is
// converted to 0, which is neutral for OR operation; otherwise, we
// get 0 | 1, which is neutral for multiplication...
product *= modulo | (modulo == 0);
}
number += product;
std::cout << ", " << number;
}
This would work fine even for fare more numbers than just the first ten ones (until overflow of either the product or the sum occurs...).

Related

Count of binary numbers from 1 to n

I want to find the number of numbers between 1 and n that are valid numbers in base two (binary).
1 ≤ n ≤ 10^9
For example, suppose n is equal to 101.
Input: n = 101
In this case, the answer is 5
Output: 1, 10, 11, 100, 101 -> 5
Another example
Input: n = 13
Output: 1, 10, 11 -> 3
Here is my code...
#include <iostream>
using namespace std;
int main()
{
int n, c = 0;
cin >> n;
for (int i = 1; i <= n; ++i)
{
int temp = i;
bool flag = true;
while(temp != 0) {
int rem = temp % 10;
if (rem > 1)
{
flag = false;
break;
}
temp /= 10;
}
if (flag)
{
c++;
}
}
cout << c;
return 0;
}
But I want more speed.
(With only one loop or maybe without any loop)
Thanks in advance!
The highest binary number that will fit in a d-digit number d1 d2 ... dn is
b1 b2 ... bn where
bi = 0 if di = 0, and
bi = 1 otherwise.
A trivial implementation using std::to_string:
int max_binary(int input) {
int res = 0;
auto x = std::to_string(input);
for (char di : x) {
int bi = x == '0' ? 0 : 1;
res = 2 * res + bi;
}
return res;
}
Details:
In each step, if the digit was one, then we add 2 to the power of the number of digits we have.
If the number was greater than 1, then all cases are possible for that number of digits, and we can also count that digit itself and change the answer altogether (-1 is because we do not want to calculate the 0).
#include <iostream>
using namespace std;
int main()
{
long long int n, res = 0, power = 1;
cin >> n;
while(n != 0) {
int rem = n % 10;
if (rem == 1) {
res += power;
} else if (rem > 1) {
res = 2 * power - 1;
}
n /= 10;
power *= 2;
}
cout << res;
return 0;
}

Is this how you add the digits of multiple numbers? (units, tens, hundreds)

I just wanna make sure whether this code is good or it needs improvement. What do you all think?
#include <iostream>
using namespace std;
u = (a%10+b%10+c%10+d%10+e%10+f%10);
t = (a / 10 % 10 + b / 10 %10 + c / 10 % 10 + d / 10 %10 + e / 10 % 10 + f / 10 %10);
h = (a / 100 % 10 + b / 100 % 10 + c / 100 % 10 + d / 100 % 10 + e / 100 % 10 + f / 100 % 10);
cout << "The sum of the first digit is: " << u << "\n";
cout << "The sum of the second digit is: " << t << "\n";
cout << "The sum of the third digit is: " << h ;
You could make it a bit more generic in at least two ways:
Write your code for just one number.
Then loop for any input numbers.
Write your code for adding any ith digit.
So, in this case, you could just focus on how to extract the ith digit of a given number n.
What, as shown in your code, could be done with (n / divisor) % 10, where divisor would be exp(10, i), i starting from 0.
Demo
#include <algorithm> // for_each
#include <iostream> // cout
#include <numeric> // accumulate
#include <vector>
int main()
{
std::vector<int> v{123'456, 99'999, 100};
auto sum_of_ith_digit = [](const std::vector<int>& v, size_t i) {
auto divisor{1};
while (i != 0) { divisor *= 10; i--; } // 1 for digit 0, 10 for digit 1, 100 for digit 2...
return std::accumulate(std::cbegin(v), std::cend(v), 0, // for each number in v
[&divisor](auto& total, const auto& n){ // get ith digit
return total + (n / divisor) % 10; // and add it to a total,
}); // then return the total
};
auto units = sum_of_ith_digit(v, 0);
auto tens = sum_of_ith_digit(v, 1);
auto hundreds = sum_of_ith_digit(v, 2);
std::for_each(std::cbegin(v), std::cend(v), [first=true](const int n) mutable {
std::cout << (first ? "v = " : ", ") << n; first = false; });
std::cout << "\n\tunits = " << units << ", tens = " << tens << ", hundreds = " << hundreds << "\n";
}
// Outputs:
// v = 123456, 99999, 100
// units = 15, tens = 14, hundreds = 14
The code below should do exactly the same, although it could be a little easier to understand. Demo
#include <iostream> // cout
#include <vector>
int sum_of_ith_digit(const std::vector<int>& v, size_t i)
{
// 1 for digit 0, 10 for digit 1, 100 for digit 2...
int divisor{1};
while (i != 0) { divisor *= 10; i--; }
// For each number in v, get ith digit, and add it to a total, then return the total
int total{0};
for (int n : v) { total += (n / divisor) % 10; }
return total;
};
int main()
{
std::vector<int> v{123'456, 99'999, 100};
int units = sum_of_ith_digit(v, 0);
int tens = sum_of_ith_digit(v, 1);
int hundreds = sum_of_ith_digit(v, 2);
std::cout << "v = ";
bool first{true};
for (int n : v)
{
if (not first) { std::cout << ", "; }
else { first = false; }
std::cout << n;
}
std::cout << "\n\tunits = " << units << ", tens = " << tens << ", hundreds = " << hundreds << "\n";
}
// Outputs:
// v = 123456, 99999, 100
// units = 15, tens = 14, hundreds = 14

greatest divisor of a number and prime factors relation

Question is as follows :
Given two numbers n and k. For each number in the interval [1, n], your task is to calculate its largest divisor that is not divisible by k. Print the sum of all these divisors.
Note: k is always a prime number.
t=3*10^5,1<=n<=10^9, 2<=k<=10^9
My approach toward the question:
for every i in range 1 to n, the required divisors is i itself,only when that i is not a multiple of k.
If that i is multiple of k, then we have to find the greatest divisor of a number and match with k. If it does not match, then this divisor is my answer. otherwise, 2nd largest divisor is my answer.
for example,take n=10 and k=2, required divisors for every i in range 1 to 10 is 1, 1, 3, 1, 5, 3, 7, 1, 9, 5. sum of these divisors are 36. So ans=36.
My code,which works for a few test cases and failed for some.
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
ll div2(ll n, ll k) {
if (n % k != 0 || n == 1) {
return n;
}
else {
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
ll aa = n / i;
if (aa % k != 0) {
return aa;
}
}
}
}
return 1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
ll n, k;
cin >> n >> k;
ll sum = 0, pp;
for (pp = 1; pp <= n; pp++) {
//cout << div2(pp, k);
sum = sum + div2(pp, k);
}
cout << sum << '\n';
}
}
Can someone help me where I am doing wrong or suggest me some faster logic to do this question as some of my test cases is showing TIME LIMIT EXCEED
after looking every possible explanation , i modify my code as follows:
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
ll n, i;
ll k, sum;
cin >> n >> k;
sum = (n * (n + 1)) / 2;
for (i = k; i <= n; i = i + k) {
ll dmax = i / k;
while (dmax % k == 0) {
dmax = dmax / k;
}
sum = (sum - i) + dmax;
}
cout << sum << '\n';
}
}
But still it is giving TIME LIMIT EXCEED for 3 test cases. Someone please help.
Like others already said, look at the constraints: t=3*10^5,1<=n<=10^9, 2<=k<=10^9.
If your test has a complexity O(n), which computing the sum via a loop has, you'll end up doing a t * n ~ 10^14. That's too much.
This challenge is a math one. You'll need to use two facts:
as you already saw, if i = j * k^s with j%k != 0, the largest divisor is j;
sum_{i=1}^t i = (t * (t+1)) / 2
We start with
S = sum(range(1, n)) = n * (n+1) / 2
then for all number of the form k * x we added too much, let's correct:
S = S - sum(k*x for x in range(1, n/k)) + sum(x for x in range(1, n/k))
= S - (k - 1) * (n/k) * (n/k + 1) / 2
continue for number of the form k^2 * x ... then k^p * x until the sum is empty...
Ok, people start writing code, so here's a small Python function:
def so61867604(n, k):
S = (n * (n+1)) // 2
k_pow = k
while k_pow <= n:
up = n // k_pow
S = S - (k - 1) * (up * (up + 1)) // 2
k_pow *= k
return S
and in action here https://repl.it/repls/OlivedrabKeyProjections
In itself this is more of a mathematical problem:
If cur = [1..n], as you have already noticed, the largest divisor = dmax = cur is, if cur % k != 0, otherwise dmax must be < cur. From k we know that it is at most divisible into other prime numbers... Since we want to make sure that dmax is not divisible by k we can do this with a while loop... whereby this is certainly also more elegantly possible (since dmax must be a prime number again due to the prime factorization).
So this should look like this (without guarantee just typed down - maybe I missed something in my thinking):
#include <iostream>
int main() {
unsigned long long n = 10;
unsigned long long k = 2;
for (auto cur_n = decltype(n){1}; cur_n <= n; cur_n++)
{
if (cur_n % k != 0) {
std::cout << "Largest divisor for " << cur_n << ": " << cur_n << " (SELF)" << std::endl;
} else {
unsigned long long dmax= cur_n/k;
while (dmax%k == 0)
dmax= dmax/k;
std::cout << "Largest divisor for " << cur_n << ": " << dmax<< std::endl;
}
}
}
I wonder if something like this is what One Lyner means.
(Note, this code has two errors in it, which are described in the comments, as well as can be elucidated by One Lyner's new code.)
C++ code:
#include <vector>
#include <iostream>
using namespace std;
#define ll long long int
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
ll n;
ll k, _k, result;
vector<ll> powers;
cin >> n >> k;
result = n * (n + 1) / 2;
_k = k;
while (_k <= n) {
powers.push_back(_k);
_k = _k * k;
}
for (ll p : powers) {
ll num_js = n / p;
result -= num_js * (num_js + 1) / 2 * (p - 1);
int i = 0;
while (p * powers[i] <= n) {
result += powers[i] * (p - 1);
i = i + 1;
}
}
cout << result << '\n';
}
}

I have to change my number last digit and first digit but without using functions only with integers or loops. For example from 12345 to 52341

#include <iostream>
using namespace std;
int main()
{
// Here I seperate my number because at first I have to seperate and then I have to change the first digit and last digit.
int numri, shifrat, i = 0, a, shuma = 0, m, d;
cout << "Jep nje numer \n";
cin >> numri;
m = numri;
while (numri != 0) {
i++;
numri = numri / 10;
}
d = pow(10, i - 1);
numri = m;
while (numri != 0) {
shifrat = numri / d;
cout << shifrat << " ";
numri = numri % d;
d = d / 10;
}
//Now after that I have to change the last digit and first digit. Please help me.
//But I'm not allowed to use functions or swap only integers and loops or conditions.
cin.get();
}
Can someone help me please?
It is more about maths than anything else.
To get the last digit of an integer we can use modulo:
z = abc....xyz % 10
To "remove" that digit from the number we use
abc...xy = abc...xyz / 10
(where / denotes integer division, ie 34/10 == 3).
I think this is what you already know how to do. Instead of deep diving into code, you should have done the maths also for the missing part first.
To add a digit to an integer we do
abc...xyz = (abc...xy * 10) + z
Only now you have all pieces necessary to start writing code:
int main() {
int inp;
int outp = 0;
std::cin >> inp; // read_input
while(inp > 0) { // reverse
int digit = ... // get_digit
inp = ... // remove_digit
outp = ... // add_digit
}
std::cout << outp;
}
It is unfortunate that you are not allowed to use functions. One of the next lessons should be that functions are much better than comments in naming things and making your code explicit
int read_input();
int remove_digit(int x);
int add_digit(int x,int digit);
int reverse(int x);
int main() {
int inp = read_input();
std::cout << reverse(inp);
}
The program can be written without using the function pow.
Here you are.
#include <iostream>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0 - exit): ";
unsigned int n;
if ( not ( std::cin >> n ) or n == 0 ) break;
std::cout << '\n';
const unsigned int Base = 10;
unsigned int factor = 1;
while ( not ( n / factor < Base ) ) factor *= Base;
unsigned int last_digit = n / factor;
unsigned int first_digit = n % Base;
n %= factor;
n = n - first_digit + last_digit;
first_digit *= factor;
n = first_digit + n;
std::cout << n << "\n\n";
}
return 0;
}
The program output might look like
Enter a non-negative number (0 - exit): 987654321
187654329
Enter a non-negative number (0 - exit): 12345
52341
Enter a non-negative number (0 - exit): 100
1
Enter a non-negative number (0 - exit): 1
1
Enter a non-negative number (0 - exit): 0
If these statements
if ( not ( std::cin >> n ) or n == 0 ) break;
and
while ( not ( n / factor < Base ) ) factor *= Base;
contain symbols that you do not know yet then you can rewrite them like
if ( !( std::cin >> n ) || n == 0 ) break;
and
while ( !( n / factor < Base ) ) factor *= Base;
You can create a program with 4 variables - n, the given number, cn - the created number, u - the last digit of the given number and p - the 10^p number;
You will save the last n digit and create the 10^p number in while. Then, using the formula
cn = ((u * p + cn % p) /10) * 10 + n;
you will create the new number;
#include <iostream>
using namespace std;
int main() {
int n, cn, u, p;
cin>>n;
u = n % 10;
cn = n;
p = 1;
while(n>9) {
p = p * 10;
n = n / 10;
}
cn = ((u * p + cn % p) /10) * 10 + n;
cout<<cn;
return 0;
}
To exchange first and last digit in a number ABCDEF --> FBCDEA
num = 12345
res = 52341
the idea is that :
52341 = 12345 - 10005 + 50001
first digit fd = num % 10
decimal places multiplier df = 1
until num is not zero we do
last digit ld = num
num = num / 10
if num != 0 decimal places multiplier df = df*10
result = ABCDEF - F - A*100000 + A + F*100000
int m = numri;
int ld = 0; // last digit(most)
int fd = numri % 10; // first digit(least)
int df = 1; // last digit multiplier 10^n where n is decimal places
while (numri != 0) {
ld = numri;// this will be the last digit in last iteration
numri = numri / 10;
if(numri) df = df * 10;
}
int res = m - fd - ld * df + fd * df + ld;
cout<<res;
example:
if the num = 12345
fd = 12345 % 10 =5
df = 1
num = 12345 / 10 = 1234
df = df*10 = 10
num = 1234 / 10 = 123
df = df*10 = 100
num = 123 / 10 = 12
df = df*10 = 1000
fd = num = 12
num = 12 / 10 = 1
df = df*10 = 10000
fd = num = 1
num = 1/10 =0
df not changed
loop exit
result = 12345 - 5 - 1*10000 + 1 + 5*10000 = 62341

Find the sum of digits of a sequence of integers

I made up my mind to write a little piece of code that gets two integers, lets say M and N ( M <= N ) and sum the digits of all the integers between them, inclusive. So for example if M = 1 and N = 9, DigitSum will equal to 45. If M = 10 and N = 11 the sum will be (1 + 0 (10) + 1 + 1 (11) = 3).
Here is my code so far (Done the for loop instead of the return):
#include <iostream>
#include <vector>
using namespace std;
// the partial digits sums digitSum[i] = the sum of the digits between 0 and i
int digitSum[] = {0, 1, 3, 6, 10, 15, 21, 28, 36, 45};
int pow_of_ten[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
// the sums of all the digits in the numbers from 1 to (10^(i) - 1) where i is the index in the array
long subsums[] = {0, 45, 20 * 45, 300 * 45, 4000 * 45, 50000 * 45, 600000 * 45, 7000000 * 45, 80000000 * 45,
900000000 * 45};
//Calculates the sum of all digits between 0 and M inclusive
long Digit_Sum(int M) {
if (M < 10) {
return digitSum[M];
}
long result = 0;
int same = M;
int counter = 0;
int lastdigit = 0;
while (same > 0) {
if (same < 10) {
lastdigit = same;
break;
}
same /= 10;
counter ++;
}
for(;counter >= 0; counter --) {
result += (subsums[counter] + M % pow_of_ten[counter] + 1) * lastdigit;
result += digitSum[lastdigit - 1] * pow_of_ten[counter];
if (counter == 0) {
break;
}
lastdigit = (M / pow_of_ten[counter - 1]) % 10;
}
return result;
}
int main() {
int M;
int N;
vector<long> sums;
while (true) {
cin >> M >> N;
if (M == 0 && N == 0) {
break;
}
sums.push_back(Digit_Sum(N) - Digit_Sum(M - 1));
}
for (vector<long>::iterator it = sums.begin(); it != sums.end(); ++it) {
cout << *it << endl;
}
}
For most cases this works well but an Online judge says it is wrong. I looked at other solutions that work but no one hard-coded the values in arrays the way I did. May this cause a partial problem, any ideas?
You can easily just create a for-loop to greatly simplify this code.
There is no need to go through all that effort.
for (Initialization Action, Boolean Expression, Update_Action)
Re deletion below: sorry, I have a bit influenza and mizread N as M. :(
I think a main error is M-1 in
sums.push_back(Digit_Sum(N) - Digit_Sum(M - 1));
Also noting that <when corrected that formula will only work for single-digit numbers. My comment earlier about using a simple formula was based on misunderstanding your problem description, in view of that formula and your examples. Both indicated single digit numbers only.
However, the complexity of the code appears unreasonably high. Consider this, assuming non-negative integers as input, and assuming m is always less than or equal to n:
#include <iostream>
#include <stdexcept>
using namespace std;
bool throwX() { throw std::runtime_error( "Ouch." ); }
auto main() -> int
{
for( ;; )
{
int m, n;
cin >> m >> n || throwX();
if( m == 0 && n == 0 ) { break; }
int sum = 0;
for( int i = m; i <= n; ++i )
{
for( int v = i; v != 0; v /= 10 )
{
sum += v % 10;
}
}
cout << sum << endl;
}
}
It needs not be more complicated than that.
Tested and working to spec, sans console input:
#include <iostream>
#include <string>
using namespace std;
void sum_a_to_b(const int & a, const int & b)
{
if (a <= b && a >= 0)
{
long long sum = 0;
for (int i = a; i <= b; i++)
{
sum += i;
}
cout << "Sum of digits from " << a << " through " << b << " is " << sum << ".\n";
}
}
int main()
{
sum_a_to_b(5, 6);
sum_a_to_b(1, 9);
}