c - Return result less than 2seconds -


i have exercise tells me calculate square root, program returns result in 6 seconds, how can return square root in less 2 seconds?

this implementation

  1 /* ************************************************************************** */   2 /*                                                                            */   3 /*                                                        :::      ::::::::   */   4 /*   ft_sqrt.c                                          :+:      :+:    :+:   */   5 /*                                                    +:+ +:+         +:+     */   6 /*   by: wjean-ma <wjean-ma@student.42.fr>          +#+  +:+       +#+        */   7 /*                                                +#+#+#+#+#+   +#+           */   8 /*   created: 2015/07/13 13:28:12 wjean-ma          #+#    #+#             */   9 /*   updated: 2015/07/14 16:48:21 wjean-ma         ###   ########.fr       */  10 /*                                                                            */  11 /* ************************************************************************** */  12  13 int     ft_sqrt(int nb)  14 {  15     int i;  16     int a;  17  18     = 0;  19     = 0;  20     if (nb <= 0)  21         return (0);  22     while (i < nb)  23     {  24         = nb - (i * i);  25         if (a == 0)  26             return (i);  27         else if (a < 0)  28             return (0);  29         ++i;  30     }  31     return (i);  32 } 

newton's method easy method implement , fast enough. see https://mitpress.mit.edu/sicp/chapter1/node9.html

the idea keep averaging current_guess , argument / curent_guess until guess close enough. example:

#include <stdio.h> #include <stdlib.h>   double square_root(double num) {     double result = 1;     double range = num * 0.001; /* answer within 1/10 of percent. */     while(abs(result*result - num) > range) {         result = (result + num/result) / 2;     }     return result; }  int main(int argc, char *argv[], char *envp[]) {     if(argc < 2) {         fprintf(stderr, "usage: %s <number>\n", argv[0]);         return 1;     }     printf("%g\n", square_root(atof(argv[1])));     return 0; } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -