I've been trying to do this but I'm getting an error Time Limit Exceeded, please help!
Example of input and exepected output
Input#1: 5 2 Output#1: 2 1
#include<stdio.h>
int main(){
long long n, k, p, r;
scanf("%lld %lld", &n, &k);
if (r >= 0 && r < k){
if (n >= 1){
p = (n - r) / k;
r = n / (p * k);
}
}
printf("%lld %lld", p, r);
return 0;
}
CodePudding user response:
Here you can take the reference from the code written in python, I first calculate the highest multiple of k (less than k
) divisible by n
. It is calculated by the //
operator in python. Like, 37/5=7.4
but 37//4 gives 7
(floor of 7.4). Then I calculate r
and finally prints them
# 37 = p*5 r
# take n=37 and k=5
n,k = map(int,input().split()) # take n,k as input
p = n//k # it will max multiple of k divisible by n
r = n - (p*k) # r = 37 - (7*5)
print("p =",p," and r=",r) # print answer here
CodePudding user response:
The variable r
is not initialized and has an indeterminate value
long long n, k, p, r;
So this if statement
if (r >= 0 && r < k){
at once invokes undefined behavior.
What you need is to include the header
#include <stdlib.h>
and to use the function lldiv
declared in this header that calculates the quotient and the remainder of two numbers.
Here is a demonstration program.
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
long long int n = 100, k = 13;
lldiv_t result = lldiv( n, k );
long long int p = result.quot;
long long int r = result.rem;
printf( "p = %lld, r = %lld\n", p, r );
}
The program output is
p = 7, r = 9
Or instead of the function you could use the two operators /
and %
like
p = n / k;
r = n % k;