In: Computer Science
C Programming
Please modify this code to display the "guess" value from the calculation and the "iterations" it took to complete. Please also add the input to the program.
Input: Program will prompt the user to provide the desired decimal-place accuracy, in the range of [1-15], inclusive. User prompt must clearly indicate what is a valid input. User input must be validated - ensuring that the value entered is an integer in the above range.
Sample output for one perfect number would look something like:
This may take up to 30 seconds to complete...
Perfect number: 6 = 1 + 2 + 3;
Initial “guess” = 2.0
Expected square root of 6 = 2.4494897...
Computed square root of 6 = 2.4494897...
reached in 8 iterations
using threshold of 0.0000...
for 12 decimal-place accuracy
#include <stdio.h>
int square(int n)
{
int a = n;
int b = 1;
int count = 0;
int e = 0.000001;
while(a - b > e)
{
a = (a + b)/2;
b = n/a;
++count;
}
return a;
}
int main(void) {
// your code goes here
int sum=0,p,i,j =0;
int arr[4],k;
printf("\n Perfect numbers between 1 and 100 are: ");
for(i= 1; i<= 10000; i++){
p=1;
while(p<=(i/2)){
if(i % p == 0)
sum=sum+p;
p++;
}
if(sum==i)
{
arr[j] = i;
printf("%d\t",arr[j]);
++j;
}
sum=0;
}
k = sizeof(arr) / sizeof(int);
for(int l = 0;l<k;l++)
{
printf("\nthe perfect number is %d\n",arr[l]);
printf("expected squareroot is %lf\n",sqrt(arr[l]));
printf("computed square root is %lf\n",square(arr[l]));
}
return 0;
}
//The program has been executed successfully
//the program calculates specific to decimals given by variable dec
//the progam takes much time for dec values greater than 6
#include <stdio.h>
#include <math.h>
float square(int n,int dec)
{
float a = n;
float b = 1;
int count = 0;
float e = 1;
for(int i=0;i<dec;i++)
{
e=e/10;
}
while(a - b > e)
{
a = (a + b)/2;
b = n/a;
count++;
}
printf("Number of iterations %d \n",count);
return a;
}
int main(void) {
// your code goes here
int sum=0,p,i,j =0;
int arr[2],k,dec;
scanf("%d",&dec);
if((dec==0)||(dec>15))
{
printf("Decimal not in Range");
return(0);
}
printf("\n Perfect numbers between 1 and 100 are: ");
for(i= 1; i<= 100; i++){
p=1;
while(p<=(i/2)){
if(i % p == 0)
sum=sum+p;
p++;
}
if(sum==i)
{
arr[j] = i;
printf("%d\t",arr[j]);
++j;
}
sum=0;
}
k = sizeof(arr) / sizeof(int);
for(int l = 0;l<k;l++)
{
printf("\nthe perfect number is %d\n",arr[l]);
printf("expected squareroot is %lf\n",sqrt(arr[l]));
printf("computed square root is %lf\n",square(arr[l],dec));
}
return 0;
}