Even though I use % 1000000007 it still results on 0 [duplicate] - c

This question already has answers here:
Need help in mod 1000000007 questions
(4 answers)
Closed 4 years ago.
my goal on this code is to make exponential operations without pow().
It works for evey value a^b which b <= 30. I'm aware that I should be using x % 1000000007 to prevent integers overflows.
#include <stdio.h>
int main(void) {
int i, a, b, rst;
rst = 1;
scanf("%d %d", &a, &b);
for (i = 0; i < b; i++){
rst = rst * a;
if( b == 0){
rst = 1;
}
}
printf("%d\n", rst % 1000000007);
return 0;
}
Why does it returns a "0" for example on "2^40 % 1000000007" even though I'm using % 1000000007?

First, you don't need if statement in for loop.
Second, you are trying to stop integer overflow after it already happens. So you need to do it after every multiplication operation.
Third, you can use unsigned long long int instead of int, because int is machine dependent (may be 1000000007 is too big for int on your machine).
I guess this should work:
#include <stdio.h>
int main()
{
unsigned long long int i, a, b, rst;
scanf("%llu %llu", &a, &b);
rst = 1;
for (i = 0; i < b; i++){
rst = (rst * a) % 1000000007;
}
printf("%llu\n", rst);
return 0;
}

Related

How to put different digits in different sides

How to write a program in c that gets single integer and another integer that is more than 3 digits at least and after that the single integer goes to the left side of the three digits number and the right side as well.
Note: I need help for the left side right side number
For example:
I mean if I got 5 and 100
it should be 51005
something like this:
int a = 5, b = 100;
int length = 1;
int tmp = b;
while (tmp /= 10)
length++;
int left = 10;
for (int i = 0; i < length; i++)
left *= 10;
int result = (left * a) + (10 * b) + a;
std::cout << result;
Also, you can play here.
there are so many methods :
one is stated in the reply above by #MikeCAT .
int a = 5, b = 100; printf("%d%d%d\n", a, b, a);
you can also try to transfer them to strings , contact them and put it back as an int if you're asked to have a variable named as c using itoa and atoi with a very static manner
char string[100],string1[100],string2[210];
int a,b,c;
scanf("%d %d",&a,&b);
itoa(a,string,10);
itoa(b,string1,10);
string2 = string+string1+string;
c=atoi(string2);
printf("Your number %d",c);
you can also try to think about it mathematically
int a,b;
scanf("%d %d",&a,&b);
int x=b,i=0,c=a;
while (x!=0) { // to get the length of b
i++;
x= x/10; }
int j ;
for (j=1;j<i;j++)
c=c*10;
c=c+b+a;
printf("your number is %d",c);
etc etc

Weird compilation issues

#include <stdlib.h>
#include <math.h>
#include <stdio.h>
int rev (int N);
int rev(int N){
return ((N <= 9)) ? N : rev(N / 10) + ((N % 10) * (pow(10, (floor(log10(abs(N))))))) ;
}
int main(void){
int r, n;
scanf("%d", &n);
r = rev(n);
printf("%d %d", r, n);
return EXIT_SUCCESS;
}
A simple code just to find out the reverse of a number. Everything is fine. Until I put a number with more than 2 digits. Things behave weirdly, somehow the last digit is always 0 of the reversed number. I have checked out in online compilers where things behave just fine. However the problem arises when I run the code on my own machine. I am on Windows 10 with MINGw. Could you guys suggest me a solution. I previously had problems where the value stored in an int matrix changes to huge values which is practically impossible to store in int due to it's size.
Using the pow and floor function, working with floats will not always round the way you'd expect.
As already commented, work with integers.
Propose doing this digit-by-digit, and sticking with integers. A proposal for your rev() function:
int rev(unsigned int N)
{
unsigned int res = 0;
while(N>0)
{
// pick off lowest digit
unsigned int digit = N%10;
// put into result, moving up all previous digits by doing *10
res = 10*res+digit;
// remove this digit from input value
N/=10;
}
return res;
}

Struggling with PairInverse problem in c using recursion [duplicate]

I encountered a hard question I don't know the answer to: "Rearrange the digits from an integer in blocks of two with a recursive function" here's an example:
Input: 123456
unsigned long pairinvPrint(unsigned long number) {
printf("%d", number % 100);
if ((number / 100) <= 99) {
printf("%d", number / 100);
}
else {
pairinv(number / 100);
}
}
Output: 563412
More I/O Examples: 42 -> 42; 1234 -> 3412
However, the set circumstances to do this are hard (no loops, arrays, pointers, global- or static variables, no libraries) and it should not print the solution directly, rather return it upon a call like this:
printf("Rearrange int (%lu) = %lu", input, pairinvert(input));
Luckily there's one circumstance to make it easier, the number of the input digits is always even.
Now I experimented for a while, but cant come up with a working solution, except the invalid one using printf.
Does anyone have some inspiration for me or idea how to tackle this?
I'll bite :-)
unsigned long p(unsigned long p1, unsigned long p2) {
// no loops, no arrays, no pointers, no global, no static, no variables, no libraries
if (p1 < 100) return p2*100 + p1;
return p(p1/100, p2*100 + p1%100);
}
unsigned long pairinvert(unsigned long n) {
// no loops, no arrays, no pointers, no global, no static, no variables, no libraries
if (n < 100) return n;
return p(n/100, n%100);
}
// need <stdio.h> for printf()
#include <stdio.h>
int main(void) {
unsigned long input;
input = 123456;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
input = 42;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
input = 1234;
printf("Rearrange int (%lu) = %lu\n", input, pairinvert(input));
}
Following program should work.
#include <stdio.h>
void rearrange(int n, int *output) {
int lsd = 0, slsd = 0;
if(n == 0)
return;
if(n > 0) {
lsd = n%10;
}
if (n > 9) {
slsd = (n%100)/10;
}
*output = 100*(*output) + 10*slsd + lsd;
n = n/100;
rearrange(n, output);
}
int main() {
int n;
int output = 0;
scanf("%d", &n);
rearrange(n, &output);
printf("%d\n", output);
return 0;
}
It is simple to understand, so I am not writing any comments.
Note that it is tail recursive so with O2 optimization it can recurse infinitely.
Try this :
unsigned long pairinv(unsigned long number, unsigned long result) {
unsigned long n = number % 100; // Gets the two digit number
if (n == 0) return result; // If it's zero returns the result
result = result * 100 + n; // Else multiplies the result by 100, adds n
return pairinv(number / 100, result); // and continues by recursion
}
int main() {
unsigned long r= 0;
printf("%lu\n", pairinv(123456, r)); //==> 563412
return 0;
}

Problems with recursive formula [duplicate]

This question already has answers here:
Division result is always zero [duplicate]
(4 answers)
Closed 3 years ago.
I'm trying to do a recursion for my coding class in C language. For some reason, the solution that I get is wrong, event though I made sure multiple times that the formula is correct.
This is what I am supposed to replicate in code.
double recursion(int n, int k, int flag, int subN, int rep)
{
if(rep == 0)
return 0;
if(flag == 0)
return sqrt(n/subN+recursion(n, ++k, ++flag, subN-2, --rep));
else
return sqrt(k/subN+recursion(--n, k, --flag, subN-2, --rep));
}
int main()
{
int n;
scanf("%d", &n);
printf("%f", recursion(n, 0, 0, 2*n, n));
return 0;
}
For n = 6, I get 1.021897, for n = 7, I get 1.005430
My solution:
n - the number we are starting from, user inputs this number in
console
k - this integer is supposed to be that counter from 1
subN - this is the number we are dividing n with
rep - acts as a counter to know when the recursion should stop (it always ends after n cycles)
When dividing two int you get integer division, where the answer is an integer. Replace at least one of the operands with a double to get floating-point calculations.
double recursion(int n, int k, int flag, int subN, int rep)
{
if(rep == 0)
return 0;
if(flag == 0)
return sqrt((double)n/subN+recursion(n, k+1, flag+1, subN-2, rep-1));
else
return sqrt((double)k/subN+recursion(n-1, k, flag-1, subN-2, rep-1));
}
or even better just change the function signature to
double recursion(double n, double k, int flag, double subN, int rep)

How do I process the return value inf

I working through a book on C on my own. This isn't homework to be turned in. I am writing a C program to determine the largest Fibonacci number my machine can produce. And instructed to use a nonrecursive method.
My Code:
#include<stdio.h>
double fibo(int n);
int main(void)
{
int n = 0; // The number input by the user
double value; // Value of the series for the number input
while (n >= 0)
{
// Call fibo function
value = fibo(n);
// Output the value
printf("For %d the value of the fibonacci series = %.0f\n", n,
value);
n++;
}
return 0;
}
double fibo(int n)
{
int i; // For loop control variable
double one = 0; // First term
double two = 1; // Second term
double sum = 0; // placeholder
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
{
for (i = 2; i <= n; i++)
{
sum = one + two;
one = two;
two = sum;
}
}
return sum;
Code works fine but I want to to break when the output gives me the fist instance of :
For 17127 the value of the fibonacci series = inf
Is there way to us an if statement like:
if (value == inf)
break;
The simplest is to use INFINITY or isinf().
Just did a little search and found this nice trick:
...
double value, temp; // Value of the series for the number input
while (n >= 0)
{
// Call fibo function
temp = fibo(n);
if (temp - temp != 0)
break;
else
value=temp;
...
well it turns out that whats happening is when temp hits Inf the if condition temp - temp produces Nan which equals nothing and the rest is just executing break; to exit the process.
I want to to break when the output gives me the first instance of : inf
Simply test against INFINITY from <math.h>. The output will not be an exact Fibonacci number.
#include <math.h>
#include <stdio.h>
int main(void) {
double a;
double b = 0;
double c = 1;
do {
a = b;
b = c;
c = a + b;
} while (c < INFINITY);
printf("%e\n", b);
return 0;
}
Output
1.306989e+308
long double
Use the widest floating point type and look for an inexact addition.
#include <fenv.h>
#include <stdio.h>
int main(void) {
long double a;
long double b = 0;
long double c = 1;
do {
a = b;
b = c;
c = a + b;
} while (fetestexcept(FE_INEXACT) == 0);
printf("%.0Lf\n", b);
return 0;
}
Output
12200160415121876738
Integers
Use the widest type available. This is akin to #Syed.Waris unsigned long long approach. Although common that unsigned long long and uintmax_t have the same range, using uintmax_t insures the widest.
uintmax_t: The following type designates an unsigned integer type capable of representing any value of any unsigned integer type:
#include <stdint.h>
#include <stdio.h>
uintmax_t a;
uintmax_t b = 0;
uintmax_t c = 1;
do {
a = b;
b = c;
c = a + b;
} while(c >= b);
printf("%ju\n", b);
Output
12200160415121876738
String
An alternative to double or some int type, is to create a simple string add function str_add(), then quite easy to form large Fibonacci numbers.
int main(void) {
char fib[3][4000];
strcpy(fib[0], "0");
strcpy(fib[1], "1");
int i;
for (i = 2; i <= 17127 && strlen(fib[1]) < sizeof fib[1] - 1; i++) {
printf("Fib(%3d) %s.\n", i, str_add(fib[2], fib[1], fib[0]));
strcpy(fib[0], fib[1]);
strcpy(fib[1], fib[2]);
}
printf("%zu\n", strlen(fib[2]));
return 0;
}
Output
Fib(1476) 13069...(299 digits)....71632. // Exact max `double`
Fib(17127) 95902...(3569 digits)...90818.
largest Fibonacci number my machine can produce
This question is not concerned with any data type but it is concerned with machine.
The basic rule of fibonacci is this:
n = (n-1) + (n-2)
You can take a big sized unsigned long long variable and you can keep on adding. But what if that datatype is overflowed? You are not concerned with data type. Your machine may produce a number even bigger than the long long. What would that number be ? Entire bits on RAM? Hard Disk ?
Since you are required to use an iterative method and not recursive method, your teacher/book/instructor might be testing you on loops (and not any standard API). Below is sample code using unsigned long long:
#include <stdio.h>
int main ()
{
unsigned long long a = 0;
unsigned long long b = 1;
unsigned long long c = a + b;
while(c >= b)
{
a = c;
c = b + c;
b = a;
}
printf("\n%llu\n", b);
return 0;
}
Output:
12200160415121876738

Resources