How to invent a code for square-root? - c

I want to write a code for making square-root not using pow().
here is what i have tried:
#include <stdio.h>
#include <stdlib.h>
int main(){
int a,I,sum=0,cnt=0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
}
printf("answer is:%d",cnt);
return 0;
}
for numbers like 4,9,16,... it works but for numbers like 10,17,21,.. it does not work and the result is more than it shoud be.
what is the problem?

for(I=1;;I+=2){
sum+=I;
if(sum>a)
break;
cnt++;
}

#include <stdio.h>
#include <stdlib.h>
int main(){
int a,I,sum=0,cnt=0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
}
if(sum==a)
printf("answer is:%d",cnt);
else
printf("answer is:%d",cnt-1);
return 0;
}

You can try this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,I,cnt=0;
int sum = 0;
printf("enter number");
scanf("%d",&a);
for(I=1;sum<a;I+=2){
sum+=I;
cnt++;
if(sum > a) //add this if statement to decrement cnt by 1 when sum exceeds a.
cnt--;
}
printf("answer is:%d",cnt);
}
Input:
21
Output:
4

Use the Babylonian method:
double babyl_sqrt(double x)
{
double i;
for (i = x / 2; fabs(i * i - x) > 0.000001f; i = (i + x / i) / 2)
;
return i;
}

To get a rounded to nearest int, adjust the limit a little bit.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int sqrt_round(int a) {
int I;
int sum = 0;
int cnt = 0;
// for(I=1;sum<a;I+=2){
for (I = 1; (sum + I / 2) < a; I += 2) {
sum += I;
cnt++;
}
return cnt;
}
int main() {
int a;
printf("enter number");
scanf("%d", &a);
printf("answer is:%d\n", sqrt_round(a));
printf("answer is:%g\n", sqrt(a));
return 0;
}

#include<stdio.h>
int main()
{
float i,x=10;
int lp;
scanf("%f",&i);
for(lp=0;lp<5;lp++)
x=(x-((((x*x)-i))/(2*x)));
printf("sqaure root of %f=%f\n",i,x);
return 0;
}

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
public int mySqrt(int x) {
long start = 1;
long end = x;
while(start + 1< end) {
long mid = start + (end - start) / 2 ;
if(mid * mid == x) {
return (int)mid;
}else if(mid * mid < x) {
start = mid ;
}else {
end = mid;
}
}
if(end * end == x) {
return (int)end;
}
return (int)start;
}

Related

How do I get a result from a recursive function without using a global variable?

I wrote a function that reverses an integer (123 becomes 321) with recursion, and I was told that using global variables is bad practice, but I'm having trouble figuring out how to get the result from the function without using one. I tried declaring the variable inside the function, but then I get undesired results.
#include <stdio.h>
int result = 0;
int reverse_num(int num)
{
int remainder = num % 10;
if (num == 0) return 0;
result *= 10;
result += remainder;
reverse_num(num / 10);
return result;
}
int main(void)
{
int num, reversed_num;
printf("Insert number: ");
scanf("%d", &num);
reversed_num = reverse_num(num);
printf("Inverted number: %d", reversed_num);
return 0;
}
The common way to do this is to have another argument just for the accumulated result. It can be accomplished in C by splitting your function into the one called by the user and the one that does all the work.
int reverse_num_helper(int num, int result)
{
int remainder = num % 10;
if (num == 0) return result;
result *= 10;
result += remainder;
return reverse_num_helper(num / 10, result);
}
int reverse_num(int num)
{
return reverse_num_helper(num, 0);
}
(In C++ you could combine the two into int reverse_num(int num, int result = 0).)
Notice how your function is essentially unchanged.We made only two minor modifications:
returning result instead of zero when num reaches zero
invoking recursion with the modified result value
There are many ways. One way involves finding the most significant decimal digit per each recursion.
Below is an inefficient example.
Works OK for some values 0 to near INT_MAX/10.
#include <stdio.h>
int reverse_num(int num) {
if (num < 10) {
return num;
}
int pow10 = 10;
while (num/pow10 >= 10) {
pow10 *= 10;
}
int lead_digit = num/pow10;
return reverse_num(num % pow10) * 10 + lead_digit;
}
int main() {
printf("%d\n", reverse_num(123456789));
printf("%d\n", reverse_num(1));
printf("%d\n", reverse_num(100));
}
Output
987654321
1
1
Fails for others printf("%d\n", reverse_num(123000789)); --> 987321.
Improved: recursive and efficient.
static int reverse_num_helper(int num, int power10) {
if (power10 < 10) {
return num;
}
return reverse_num_helper(num % power10, power10 / 10) * 10 + num / power10;
}
int reverse_num(int num) {
int pow10 = 1;
while (num / pow10 >= 10) {
pow10 *= 10;
}
return reverse_num_helper(num, pow10);
}
int main() {
printf("%d\n", reverse_num(123000789));
printf("%d\n", reverse_num(123456789));
printf("%d\n", reverse_num(123));
printf("%d\n", reverse_num(1));
printf("%d\n", reverse_num(100));
}
Output
987000321
987654321
321
1
1
A somewhat more long-winded version of that given by #chux might be a bit clearer.
#include <stdio.h>
int count_places(int num);
int reverse_by_places(int num, int num_places);
int ipow(int base, int power);
int reverse_num(int num)
{
return reverse_by_places(num, count_places(num)) / 10;
}
int ipow(int base, int power)
{
if (power == 0)
return 1;
return base * ipow(base, power-1);
}
int count_places(int num)
{
int i;
if (num == 0)
return 1;
for (i = 0; num > 0; i++)
{
num /= 10;
}
return i;
}
int reverse_by_places(int num, int num_places)
{
int dividend = num / 10, remainder = num % 10;
if (dividend == 0)
return remainder * ipow(10, num_places);
else
return ((remainder * ipow(10, num_places)) + reverse_by_places(dividend, num_places-1));
}
int main(void)
{
int num, reversed_num;
printf("Insert number: ");
scanf("%d", &num);
reversed_num = reverse_num(num);
printf("Inverted number: %d\n", reversed_num);
return 0;
}
To keep it similar to your original code, only without the global variable, try this:
#include <stdio.h>
#define RESET (-1)
int reverse_num(int num)
{
static int result = 0;
int remainder = num % 10;
if (num < 0) {
result = 0;
return 0;
}
if (num == 0) return 0;
result *= 10;
result += remainder;
reverse_num(num / 10);
return result;
}
int main(void)
{
int num, reversed_num;
printf("Insert number: ");
scanf("%d", &num);
reverse_num(RESET);
reversed_num = reverse_num(num);
printf("Inverted number: %d\n", reversed_num);
return 0;
}
Here, I just make result into a local static variable in the function, which means it keeps its value even when the function returns (like a global variable, except that its scope is only within the function). The catch is that if you want to call it more than once, you need a way to reset the result value; I did this by using a negative value for num as a semaphore to reset.
int Reverse(int n,int Len) {
if (n == 0)
return 0;
return std::pow(10, Len-1)*(n % 10) + Reverse(n / 10, Len-1);
}
//inside main
Reverse(54321,5);
//Output Should be 12345

How can I printf the series of the following series of fraction Sn=1/n+1/(n-1)+1/(n-2)+...+1 in c programming?

How can I printf the series of the following series of fraction Sn=1/n+1/(n-1)+1/(n-2)+...+1 in c programming?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//declaring integer variables
int i,num;
//declaring float variable
float sum = 0;
printf("Enter any number: ");
scanf("%d", &num);
//creating for loop
for(i = 1; i <= num; i++) //
{
sum = sum + 1/i + 1/i-1;
if(i==num)
{
printf("1/%d=", i);
}else
{
printf(" 1/%d +", i);
}
}
printf("The sum of the series are: %f", sum);
return 0;
}```
#include <stdio.h>
#include <stdlib.h>
/* Sn=1/n+1/(n-1)+1/(n-2)+...+1 */
int
main(int argc, char **argv)
{
unsigned n = argc > 1 ? strtoul(argv[1], NULL, 0) : 10;
float sum = 1.0;
if( n ){
printf("S(%d) = ", n);
for( ; n > 1; n-- ){
sum += 1.0/n;
printf("1/%d + ", n);
}
printf("1 =~ %f\n", sum);
}
}

Why does same program act different in ideone and codeblocks?

This code is designed to find the sum of digits of 100!. I get the correct ouput in ideone but the wrong one in codeblocks. Please help.
#include <stdio.h>
#include <stdlib.h>
#define size_of_number 160
#define question 100
//Function Prototypes
void initialise(int[]);
int sum_of_digits(int[]);
void factorial(int[],int);
int main()
{
int number[size_of_number];
int sum;
initialise(number);
factorial(number, question);
//Getting the sum of the digits of the number
sum = sum_of_digits(number);
printf("The sum of the digits of %d! is %d.\n",question, sum);
return 0;
}
//Initially, the number is 0 so all it's digits are set to zero.
void initialise(int number[])
{
int i;
for(i = 0; i < size_of_number; i++)
{
number[i] = 0;
}
}
//Finding the factorial by multiplying the digits
void factorial(int number[], int num)
{
int i, first_digit;
int carry, replace, product;
first_digit = 0;
number[first_digit] = 1;
while(num != 1)
{
carry = 0;
for(i = 0; i <= first_digit; i++)
{
product = num*number[i] + carry;
replace = product%10;
carry = product/10;
number[i] = replace;
if( (i == first_digit) && (carry > 0) )
{
first_digit++;
}
}
num--;
}
}
//Finding the sum of all digits
int sum_of_digits(int number[])
{
int i, sum;
for(i = 0; i < size_of_number; i++)
{
sum = sum + number[i];
}
return sum;
}
I had problems with some other programs too. Why s Codeblocks not giving the correct output which is 648 ?
You don't initialize sum in the function sum_of_digits. Normal local variables don't automatically get a starting value in C, so your program has what the C standard calls undefined behaviour. Anything can happen, but what typically does happen is that the variable starts with whatever data happened to be in the place in memory where the variable happened to be located.

Summing an Array with random values

I need to make a function that sums my array, which is filled with random values. My function only returns 0 and not an actual summation of the array. I don't have much experience with arrays or random values, how can I code my arrSum function to give me the sum of the array when called?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000
int arrSum(int arr[SIZE], int b) {
if (b < 0) {
return 0;
} else {
return arr[b] + arrSum(arr, b - 1);
}
}
int main() {
int inputNum;
int i;
int arr1[SIZE];
int sum;
srand(time(0));
printf("Enter an integer between 0 and 1000: ");
scanf("%d", &inputNum);
sum = arrSum(arr1, inputNum);
printf("sum: %6d\n\n", sum );
printf(" Pos | Val\n");
printf("-------------\n");
for (i = 0; i < inputNum; i++) {
printf("%4d |%4d\n", i, rand() % 1001);
}
return 0;
}
The reason is initially there are no values in the array. But only 0.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000
int arrSum(int arr[SIZE], int b){
if (b < 0) return 0;
else return arr[b] + arrSum(arr, b-1);
}
int main(){
int inputNum;
int i,q;
int arr1[SIZE] = {0};
int sum;
srand(time(0));
printf("Enter an integer between 0 and 1000: ");
scanf("%d",&inputNum);
for(q=0;q<inputNum;q++){
arr1[q] = rand() % 1001;
}
sum = arrSum(arr1, inputNum);
printf("sum: %6d\n\n", sum );
printf(" Pos | Val\n");
printf("-------------\n");
for (i = 0; i < inputNum; i++){
printf("%4d |%4d\n", i,arr1[i]);
}
return 0;
}
The logic behind finding the sum inside the function is correct, assuming that b is within the range of the array indices. The real problem is that your array is not filled with random numbers - it is filled with zeros.
When you do
int arr1[SIZE] = {0};
you are initializing each element to 0, and are not changing it at any point during the program. So, your function returns the sum from indices 0 to b, but this turns out to be 0.

Find 10000th prime number [duplicate]

This question already has answers here:
Prime Number Algorithm
(7 answers)
Closed 8 years ago.
This is my code for finding 10000th prime number but it is really slow, it takes 7 seconds to calculate.
#include <stdio.h>
#include <stdlib.h>
long int prime (int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
int main()
{
int i=2,counter=0;
while(1)
{
if(prime(i))
counter++;
if(counter==10000)
break;
i++;
}
printf("10000th prime number is: %d",i);
}
It is brute force method so that's probably reason why it's so slow.
I think problem may be that it has to call function so many times. So what do you think can it be optimised or it's better to find some math formula for this.
You can reduce the time substantially by making the following changes to prime():
Stopping at sqrt(n).
Starting at i=3, and incrementing i by 2.
Here's a program that contains both versions and the time taken by each.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
int is_prime1 (int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
void do_it1(int max)
{
clock_t start = clock();
clock_t end;
int i=2,counter=0;
while(1)
{
if(is_prime1(i))
counter++;
if(counter==max)
break;
i++;
}
end = clock();
printf("%dth prime number is: %d\n", max, i);
printf("Time taken: %lf\n", 1.0*(end-start)/CLOCKS_PER_SEC);
}
int is_prime2 (int n)
{
int i;
int stop = sqrt(n);
for(i=3;i<=stop;i+=2)
{
if(n%i==0)
return 0;
}
return 1;
}
void do_it2(int max)
{
clock_t start = clock();
clock_t end;
int i=3,counter=1;
while(1)
{
if(is_prime2(i))
counter++;
if(counter==max)
break;
i += 2;
}
end = clock();
printf("%dth prime number is: %d\n", max, i);
printf("Time taken: %lf\n", 1.0*(end-start)/CLOCKS_PER_SEC);
}
int main(int argc, char** argv)
{
int max = atoi(argv[1]);
do_it1(max);
do_it2(max);
}
Sample execution:
./test 10000
Sample output:
10000th prime number is: 104729
Time taken: 9.469000
10000th prime number is: 104729
Time taken: 0.078000
To optimized your code a little bit (changes are made based on comments):
long int prime (int n)
{
int i;
int e = (int)sqrt(n);
for(i=2; i<=e;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int *prime;
int prime_n;
void make_prime_table(int n){
prime = malloc(sizeof(int) * n / 2);
prime_n =0;
prime[prime_n++] = 2;
prime[prime_n++] = 3;
int i, j;
for(i = 5; i <= n; i +=2){
bool is_prime = true;
for(j = 1; j < prime_n ; ++j){
int t = prime[j];
if(t * t > i)
break;
if(i % t == 0){
is_prime = false;
break;
}
}
if(is_prime)
prime[prime_n++] = i;
}
}
int main(void){
int n = 105000;
make_prime_table(n);
if(prime_n >= 10000)
printf("10000th prime number is: %d\n", prime[9999]);
free(prime);
return 0;
}

Resources