For loop divide numbers - c++

I'm an amateur when it comes to C++ but I've already received a task which is over my knowledge.
Task is to enter numbers n,m. Programme must take it as an interval, in which it checks if there is any number which is a sum of numbers with the same exponent.
EDIT:(18.10.15)
Turns out I didn't understood my task correctly. Here it is:
"User enter two numbers. Programme takes it as the interval in which it checks all the numbers. If there's a number in interval which all digit's sum of SAME exponent is that number, then programme shows it."
For example, I enter 100 and 200. In this interval there's 153.
153 = 1^3 + 5^3 + 3^3 (1+125+27)
Programme shows 153.
cin >> n;
cin >> m;
for (int i=n; i<=m; i++)
{
for (int k=n; k<=i; k++)
{
a = n % 10; //for example, I enter 153, then a=3
f = n /= 10; //f=15
b = f % 10; //b=5
f = f /= 10; //f=1
c = f % 10; //c=1
f = f /= 10;
d = f % 10;
for (int j=1; j<=5; j++)
{
a = a * a;
b = b * b;
c = c * c;
d = d * d;
if (a + b + c + d == n)
{
cout << n << endl;
}
}
}
}
Any help will be appreciated.

Task is to enter numbers n,m. Programme must take it as an interval, in which it checks if there is any number which is a sum of numbers with the same exponent.
Assuming the range is given as [n, m), then here's your program:
return (n != m);
Any number can be seen as a sum of numbers with the same exponent. For example:
0 = 0 ^ 3 + 0 ^ 3 + 0 ^ 3
1 = 1 ^ 3 + 0 ^ 3
2 = 1 ^ 3 + 1 ^ 3
3 = 1 ^ 3 + 1 ^ 3 + 1 ^ 3
and so on. This is true even for negative numbers.
So in any non-empty range there exists at least 1 such number.

"All I know is how to get the programm to check each number separately"
"Programme must not use arrays."
for (int i = n; i <= m; i++) {
...
int x = (int)Math.log10(i);
int rest = i;
for (int p = x; p>=0; p--) {
int digit = rest / (int)Math.pow(10,p);
rest = i % (int)Math.pow(10,p);
//3802 = 3*10^3 + 8*10^2 + 0*10^1 + 2*10^0
}
}
...
Sorry, is Java no C++

Sorry that I answer so late and that I phrased my question poorly - English isn't my native language.
But turns out I didn't understood my task correctly. Here it is:
"User enter two numbers. Programme takes it as the interval in which it checks all the numbers. If there's a number in interval which all digit's sum of SAME exponent is that number, then programme shows it."
For example, I enter 100 and 200. In this interval there's 153.
153 = 1^3 + 5^3 + 3^3 (1+125+27)
Programme shows 153.
cin >> n;
cin >> m;
for (int i=n; i<=m; i++)
{
for (int k=n; k<=i; k++)
{
a = n % 10; //for example, I enter 153, then a=3
f = n /= 10; //f=15
b = f % 10; //b=5
f = f /= 10; //f=1
c = f % 10; //c=1
f = f /= 10;
d = f % 10;
for (int j=1; j<=5; j++)
{
a = a * a;
b = b * b;
c = c * c;
d = d * d;
if (a + b + c + d == n)
{
cout << n << endl;
}
}
}
}

Related

Code Chef DSA Learning Series : Multiple of 3

Consider a very long K-digit number N with digits d0, d1, ..., dK-1 (in decimal notation; d0 is the most significant and dK-1 the least significant digit). This number is so large that we can't give it to you on the input explicitly; instead, you are only given its starting digits and a way to construct the remainder of the number.
Specifically, you are given d0 and d1; for each i ≥ 2, di is the sum of all preceding (more significant) digits, modulo 10 — more formally, the following formula must hold:
Determine if N is a multiple of 3.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains three space-separated integers K, d0 and d1.
Output
For each test case, print a single line containing the string "YES" (without quotes) if the number N is a multiple of 3 or "NO" (without quotes) otherwise.
Constraints
1 ≤ T ≤ 1000
2 ≤ K ≤ 1012
1 ≤ d0 ≤ 9
0 ≤ d1 ≤ 9
Example
Input:
3
5 3 4
13 8 1
760399384224 5 1
Output:
NO
YES
YES
Explanation
Example case 1: The whole number N is 34748, which is not divisible by 3, so the answer is NO.
Example case 2: The whole number N is 8198624862486, which is divisible by 3, so the answer is YES.
Question Ended
In this question, in the example test case given, we have k=760399384224, d0=5, and d1=1. Now we know that a number is multiple of 3 if the sum of it’s digits is a multiple of 3. So applying it here, we separate the number n into 3 parts,
Part 1: First 3 digits -> 516 , (5+1+6) mod 3 ==0, so rem1 = 0.
Part 2: Next will be (k-3)/4 times repetition of (2486) ,or,rem2 = ((2+4+8+6)*((k-3)/4))%3= 1
Part 3: the last (k-3)%4 =1 digits which will be 2 (from 2486 repetition) , so rem3 = 2%3=2
So the final answer should be (rem1+rem2+rem3)%3
and I wrote the following code for this logic:
#include<iostream>
#define ll long long
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
ll k;
cin>>k;
int d0,d1;
cin>>d0>>d1;
int d2 = (d0+d1)%10;
int d[4];
d[0] = (d0+d1+d2)%10;
d[1] = (2*d[0])%10;
d[2] = (2*d[1])%10;
d[3] = (2*d[2])%10;
ll rem1 = (d0+d1+d2)%3,rem2,rem3=0;
rem2 = (20*(((k-3)/4)%3))%3;
ll x = (k-3)%4;
if(x!=0)
{
for(int i=0; i<x; ++i)
rem3+=d[i];
rem3 = rem3%3;
}
else
rem3 =0;
if(k==2)
{
rem1 = (d0+d1)%3;
rem2=0;
rem3=0;
}
if((rem1+rem2+rem3)%3==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
Now they’re giving me WA in their test cases. And I cant think of a possible test cases which doesn’t work with this code. So somebody help me out please.
Here's an apparent mismatch. You can probably use this JavaScript code to find more:
function f(k, d0, d1){
let d2 = (d0+d1)%10;
let d = new Array(4).fill(0);
d[0] = (d0+d1+d2)%10;
d[1] = (2*d[0])%10;
d[2] = (2*d[1])%10;
d[3] = (2*d[2])%10;
let rem1 = (d0+d1+d2)%3, rem2, rem3=0;
rem2 = (20*((~~((k-3)/4))%3))%3;
let x = (k-3)%4;
if(x!=0)
{
for(let i=0; i<x; ++i)
rem3+=d[i];
rem3 = rem3%3;
}
else
rem3 =0;
if(k==2)
{
rem1 = (d0+d1)%3;
rem2=0;
rem3=0;
}
if((rem1+rem2+rem3)%3==0)
return true
return false
}
function bruteForce(k, d0, d1){
let d = (d0 + d1) % 10;
let n = 10 * d0 + d1;
for (let i=3; i<=k; i++){
n = 10 * n + d;
d = (2 * d) % 10;
}
return [n % 3 == 0, n];
}
let str = "";
str += "Examples:\n";
str += "(5, 3, 4)\n" + bruteForce(5, 3, 4) + "\n\n";
str += "(13, 8, 1)\n" + bruteForce(13, 8, 1) + "\n\n"
var k = 7;
var mismatch = false;
for (let i=1; i<10; i++){
for (let j=0; j<10; j++){
const _f = f(k, i, j);
const _bruteForce = bruteForce(k, i, j);
if (_bruteForce[0] != _f){
str += "Mismatch:\n" +
`(${ k }, ${ i }, ${ j })\n` +
"f: " + _f +
"\nbruteForce: " + _bruteForce + "\n\n";
mismatch = true;
}
if (mismatch)
break;
}
if (mismatch)
break;
}
console.log(str);
#include <stdio.h>
void isMulti3(long long int K, long long int d0, long long int d1) {
long long int mod1 = (d0 + d1) % 10;
long long int sum_mod1 = d0 + d1 + mod1;
long long int rep = (K-3)/4;
long long int mod2[4];
mod2[0] = (2*mod1) % 10;
mod2[1] = (4*mod1) % 10;
mod2[2] = (8*mod1) % 10;
mod2[3] = (6*mod1) % 10;
long long int sum_mod2 = 0;
for(int i = 0; i < 4; i++) {
sum_mod2 += mod2[i];
}
long long int unrep = (K - 3) % 4;
long long int sum_mod3 = 0;
for(int i = 0; i < unrep; i++) sum_mod3 += mod2[i];
long long int isMod1 = sum_mod1 % 3;
long long int isMod2 = ((rep%3)*(sum_mod2%3)) % 3;
long long int isMod3 = sum_mod3 % 3;
if((isMod1 + (isMod2 + isMod3)%3)% 3 == 0) printf("YES\n");
else printf("NO\n");
}
int main() {
int T;
scanf("%d", &T);
for(int i = 0; i < T; i++) {
long long int K;
long long int d0, d1;
scanf("%lld %lld %lld", &K, &d0, &d1);
if(K == 2) {
if((d0 + d1) % 3 == 0) printf("YES\n");
else printf("NO\n");
}
else isMulti3(K, d0, d1);
}
}
I think you are the same guy who asked the question on the codechef discussion portal.
I answered it there , and I am sharing the link.
[https://discuss.codechef.com/t/dsa-learning-series-multiple-of-3/77174/4?u=nazishkaunain][1]
So the point where you are mistaken is:
You might use the fact:
(a+b+c)mod 3 != a mod 3 + b mod 3 + c mod 3;
But (a + b + c) mod 3 = (a mod 3 + ( b mod 3 + c mod 3) mod 3) mod 3;
And a number n ( n = a + b + c) is divisible by 3 only if n mod 3 = 0 => (a + b + c) mod 3 = 0.

Explanation of the algorithm to find a number 'm' made up of digits 0's and 1's which is divisible by the number n

Here's a piece of code from a udemy course that I am currently taking that uses the pigeon hole principle to find a number made up of 0's and 1's divisible by the number n.
void findNumber(int n) {
int cur_rem = 0;
for(int i = 1; i <= n; i++) {
cur_rem = (cur_rem * 10 + 1) % n;
if(cur_rem == 0) {
for(int j = 1; j <= i; j++)
cout << 1;
return;
}
if(fr[cur_rem] != 0) {
for(int j = 1; j <= i - fr[cur_rem]; j++)
cout << 1;
for(int j = 1; j <= fr[cur_rem]; j++)
cout << 0;
return;
}
fr[cur_rem] = i;
}
}
So, in this code we actually first take the numbers 1,11,111,...,111..1(n times) and see if they are divisible by the given integer n. If they are not divisible then we find the 2 numbers within 1,11,111,...111..1(n times) with the same remainder when divided by the number n and subtract them to get the number that is divisible by n. So, I understand the theory part but I did not understand one line of the code.
Can someone please explain to me this line of code: cur_rem = (cur_rem * 10 + 1) % n; how can we get the remainder of the current number by multiplying the remainder of the previous number by 10 and then adding 1 and then finding the mod by dividing the sum by the given integer n?
Suppose the last number 111... (we'll call it m), had remainder r.
m % n = r
m = kn + r
Now the next number, 111..., call it m', is one digit longer than m.
m' = 10 m + 1
m' % n = (10 m + 1) % n
= (10(kn + r) + 1) % n
= (10 kn + 10r + 1) % n
= ( 10r + 1) % 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

Trying to check for 3 of a kind with arrays (Yahtzee) C++

I am trying to check for if the kept dice rolls (which can be up to 5) are 3 of a kind or not, so I'm trying to compare the dice roll values to each other.
The first value of R is showing as 0 of course, but the second value of R after the code is run is showing as 8191 every time, and I'm not entirely sure why.
I've also tried using
r++ instead of r += r+1, but of course that didn't change anything.
int r = 0;
cout << "first value of R is " << r << endl;
for(int t = 0; t < 5; t++) {
for(int w = 0; w < 5; w++) {
if(keptDice[t] == keptDice[w] ) {
r += r + 1;
}
}
}
cout << "Value of R is " << r << endl;
The point is that in the second for loop yo have tor start from t (int w = t;...) otherwise you would compare each dice with itself which will be naturally equal. Plus use r++ instead of r += r + 1 which is definitely wrong but I think that is just a misspelling.
int r = 0;
cout << "first value of R is " << r << endl;
for(int t = 0; t < 5; t++) {
for(int w = t; w < 5; w++) {
if(keptDice[t] == keptDice[w] ) {
r++;
}
}
}
cout << "Value of R is " << r << endl;
r += r + 1
is the same as writing
r = r + r + 1
r is doubling every time. Interestingly, it's always 1 less than 2^n
r = 0 + 0 + 1 (1)
r = 1 + 1 + 1 (3)
r = 3 + 3 + 1 (7)
r = 7 + 7 + 1 (15)
r = 15 + 15 + 1 (31)
r = 31 + 31 + 1 (63)
r = 63 + 63 + 1 (127)
r = 127 + 127 + 1 (255)
r = 255 + 255 + 1 (511)
r = 511 + 511 + 1 (1023)
r = 1023 + 1023 + 1 (2047)
r = 2047 + 2047 + 1 (4095)
r = 4095 + 4095 + 1 (8191)
Your program is counting 13 matches. For yahtzee, you probably want an array that counts matches, otherwise you're doubling up on each die. For example, if you had
1 2 3 4 1
It would count the first 1 matching the last die AND the last die matching the first (2 matches).
What would be more sensible is to count how many 1's you have, how many 2s you have, and store in an array
int diceCount[6];
for(int num = 1; num <= 6; num++) {
for(int w = 0; w < 5; w++) {
int count = 0;
if(keptDice[w] == num ) {
count++;
}
diceCount[num-1] = count;
}
This way when it's done, if you had two 1's, then diceCount[0] will be 2
Based on your approach, but generalized to N-of-a-kind:
int N = 3; // N in [1;5]
bool isNOfAKind = false;
for(int t = 0; t < 6-N; t++) { // skip searches with less elements than N
int r = 0; // r must be reset for each count
for(int w = t+1; w < 5; w++) { // avoid comparing to self
if(keptDice[t] == keptDice[w]) {
r++;
}
}
// found a solution already? then bail out.
if(r == N) {
isNOfAKind = true;
break;
}
}
cout << N << " of a kind? " << isNOfAKind << endl;

Finding Pythagorean Triples: Euclid's Formula

I'm working on problem 9 in Project Euler:
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
The following code I wrote uses Euclid's formula for generating primes. For some reason my code returns "0" as an answer; even though the variable values are correct for the first few loops. Since the problem is pretty easy, some parts of the code aren't perfectly optimized; I don't think that should matter. The code is as follows:
#include <iostream>
using namespace std;
int main()
{
int placeholder; //for cin at the end so console stays open
int a, b, c, m, n, k;
a = 0; b = 0; c = 0;
m = 0; n = 0; k = 0; //to prevent initialization warnings
int sum = 0;
int product = 0;
/*We will use Euclid's (or Euler's?) formula for generating primitive
*Pythagorean triples (a^2 + b^2 = c^2): For any "m" and "n",
*a = m^2 - n^2 ; b = 2mn ; c = m^2 + n^2 . We will then cycle through
*values of a scalar/constant "k", to make sure we didn't miss anything.
*/
//these following loops will increment m, n, and k,
//and see if a+b+c is 1000. If so, all loops will break.
for (int iii = 1; m < 1000; iii++)
{
m = iii;
for (int ii = 1; n < 1000; ii++)
{
n = ii;
for (int i = 1; k <=1000; i++)
{
sum = 0;
k = i;
a = (m*m - n*n)*k;
b = (2*m*n)*k;
c = (m*m + n*n)*k;
if (sum == 1000) break;
}
if (sum == 1000) break;
}
if (sum == 1000) break;
}
product = a * b * c;
cout << "The product abc of the Pythagorean triplet for which a+b+c = 1000 is:\n";
cout << product << endl;
cin >> placeholder;
return 0;
}
And also, is there a better way to break out of multiple loops without using "break", or is "break" optimal?
Here's the updated code, with only the changes:
for (m = 2; m < 1000; m++)
{
for (int n = 2; n < 1000; n++)
{
for (k = 2; (k < 1000) && (m > n); k++)
{
sum = 0;
a = (m*m - n*n)*k;
b = (2*m*n)*k;
c = (m*m + n*n)*k;
sum = a + b + c;
if ((sum == 1000) && (!(k==0))) break;
}
It still doesn't work though (now gives "1621787660" as an answer). I know, a lot of parentheses.
The new problem is that the solution occurs for k = 1, so starting your k at 2 misses the answer outright.
Instead of looping through different k values, you can just check for when the current sum divides 1000 evenly. Here's what I mean (using the discussed goto statement):
for (n = 2; n < 1000; n++)
{
for (m = n + 1; m < 1000; m++)
{
sum = 0;
a = (m*m - n*n);
b = (2*m*n);
c = (m*m + n*n);
sum = a + b + c;
if(1000 % sum == 0)
{
int k = 1000 / sum;
a *= k;
b *= k;
c *= k;
goto done;
}
}
}
done:
product = a * b * c;
I also switched around the two for loops so that you can just initialize m as being larger than n instead of checking every iteration.
Note that with this new method, the solution doesn't occur for k = 1 (just a difference in how the loops are run, this isn't a problem)
Presumably sum is supposed to be a + b + c. However, nowhere in your code do you actually do this, which is presumably your problem.
To answer the final question: Yes, you can use a goto. Breaking out of multiple nested loops is one of the rare occasions when it isn't considered harmful.