I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
Here is my full code:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance.
Below explanation is given for the integer square root calculation:
In number theory, the integer square root of a positive
integer n is the positive integer m which is the greatest integer less
than or equal to the square root of n
The approach your started is good but needs several correction to make it work:
you are working with int you want to add 1 to squareroot not 0.1
you want to stop your calculation when you squareroot * squareroot is equal or greater than number. Think about the case were the number is 26, you don't have an integer that multiplies itself to 26.
in the case of number equal to 26, do you want to return 5 or 6? After your while loop the value of squareroot will be 6 so you might want to reverse it to 5 (if squareroot * squareroot is different than number)
Below the exemple:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot < number){
squareroot+=1;
}
if (squareroot * squareroot != number) --squareroot;
cout << "the square root is" << squareroot << endl;
return 0;
}
Below a more efficient and elegant way of calculating the square root using binary search principle. O(log(n))
int mySqrt(int x) {
if (x==0) return 0;
int left = 1;
int right = x/2 + 1;
int res;
while (left <= right) {
int mid = left + ((right-left)/2);
if (mid<=x/mid){
left = mid+1;
res=mid;
}
else {
right=mid-1;
}
}
return res;
}
This function uses Nested Intervals (untested) and you can define the accuracy:
#include <math.h>
#include <stdio.h>
double mySqrt(double r) {
double l=0, m;
do {
m = (l+r)/2;
if (m*m<2) {
l = m;
} else {
r = m;
}
}
while(fabs(m*m-2) > 1e-10);
return m;
}
See https://en.wikipedia.org/wiki/Nested_intervals
This function will calculate the floor of square root if A is not a perfect square.This function basically uses binary search.Two things you know beforehand is that square root of a number will be less or equal to that number and it will be greater or equal to 1. So we can apply binary search in that range.Below is my implementation.Let me know if you don't understand anything in the code.Hope this helps.
int sqrt(int A) {
if(A<1)return 0;
if(A==1)return 1;
unsigned long long start,end,mid,i,val,lval;
start = 1;
end = A;
while(start<=end){
mid = start+(end-start)/2;
val = mid*mid;
lval = (mid-1)*(mid-1);
if(val == A)return mid;
else if(A>lval && A<val) return mid-1;
else if(val > A)end = mid;
else if(val < A)start = mid+1;
}
}
The problem with your code, is that it only works if the square root of the number is exactly N*0.1, where N is an integer, meaning that if the answer is 1.4142 and not 1.400000000 exactly your code will fail. There are better ways , but they're all more complicated and use numerical analysis to approximate the answer, the easiest of which is the Newton-Raphson method.
you can use the function below, this function uses the Newton–Raphson method to find the root, if you need more information about the Newton–Raphson method, check this wikipedia article. and if you need better accuracy - but worse performance- you can decrease '0.001' to your likening,or increase it if you want better performance but less accuracy.
float mysqrt(float num) {
float x = 1;
while(abs(x*x - num) >= 0.001 )
x = ((num/x) + x) / 2;
return x;
}
if you don't want to import math.h you can write your own abs():
float abs(float f) {
if(f < 0)
f = -1*f;
return f;
}
Square Root of a number, given that the number is a perfect square.
The complexity is log(n)
/**
* Calculate square root if the given number is a perfect square.
*
* Approach: Sum of n odd numbers is equals to the square root of n*n, given
* that n is a perfect square.
*
* #param number
* #return squareRoot
*/
public static int calculateSquareRoot(int number) {
int sum=1;
int count =1;
int squareRoot=1;
while(sum<number) {
count+=2;
sum+=count;
squareRoot++;
}
return squareRoot;
}
#include <iostream>
using namespace std;
int main()
{
double x = 1, average, s, r;
cout << "Squareroot a Number: ";
cin >> s;
r = s * 2;
for ( ; ; ) //for ; ; ; is to run the code forever until it breaks
{
average = (x + s / x) / 2;
if (x == average)
{
cout << "Answer is : " << average << endl;
return 0;
}
x = average;
}
}
You can try my code :D
the method that i used here is the Babylonian Squareroot Method
which you can find it here https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
Related
I am new to coding and just starting with the c++ language, here I am trying to find the number given as input if it is Armstrong or not.
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153.
But even if I give not an armstrong number, it still prints that number is armstrong.
Below is my code.
#include <cmath>
#include <iostream>
using namespace std;
bool ifarmstrong(int n, int p) {
int sum = 0;
int num = n;
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
if(sum==n){
return true;
}else{
return false;
}
}
int main() {
int n;
cin >> n;
int i, p = 0;
for (i = 0; n > 0; i++) {
n = n / 10;
}
cout << i<<endl;
if (ifarmstrong(n, i)) {
cout << "Yes it is armstorng" << endl;
} else {
cout << "No it is not" << endl;
}
return 0;
}
A solution to my problem and explantation to what's wrong
This code
for (i = 0; n > 0; i++) {
n = n / 10;
}
will set n to zero after the loop has executed. But here
if (ifarmstrong(n, i)) {
you use n as if it still had the original value.
Additionally you have a error in your ifarmstrong function, this code
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
result in num being zero from the second iteration onwards. Presumably you meant to write this
while(num>0){
sum=sum+pow(num%10,p);
num=num/10;
}
Finally using pow on integers is unreliable. Because it's a floating point function and it (presumably) uses logarithms to do it's calculations, it may not return the exact integer result that you are expecting. It's better to use integers if you are doing exact integer calculations.
All these issues (and maybe more) will very quickly be discovered by using a debugger. much better than staring at code and scratching your head.
According to my lecturer a balanced number is balanced if the sum of its divisors is equal to it self. for example: 6 is a balanced number because 1+2+3=6
These are my very first homework so i am struggeling.
#include <iostream>
using namespace std;
int main() {
int num = 0;
int sum = 0;
cout << "Enter a number" << endl;
cin >> num;
if (num % (num-1) == 0 ){
for(int i =1; sum == 0; i++) {
sum += (num - i);
}
if (sum == num) {
cout << "Great Success" << endl;
}
else {
cout << "Wrong number" << endl;
}
}
}
Do the maths first. Often code being a bit messy is just a consequence of not preparing yourself good enough to write the code. Dont start writing code before you know what you want to write. Frankly, from your code one can see that it is something related to num-1 dividing num, but otherwise it is not clear how it is supposed to solve the problem. And its intendation makes it quite hard to read, so lets forget about the code and start from scratch...
y is a divisor of x exactly if x % y == 0. The biggest possible divisor of x is x/2. To get all divisors we can simply check every number from 2 up to x/2 (1 is always considered a divisor, hence no need to check).
Only now we can write some code:
int x;
std::cin >> x;
int sum = 1;
for (int y = 2; y <= x/2; ++y){
if ( check_if_y_is_divisor) { sum += y; }
}
bool is_balanced = sum == x;
I left a tiny hole in the code that you have to fill (I just dont like to give away the full solution when it is homework).
I created a prime number checking program which checks the user entered number prime or not.
It detects non prime numbers easily, but when we type prime numbers, it crashes!
I think I know why, but don't know how to rectify them...
Here's my Program:
#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
Remainder(n, x + 1 > n);
/*
Here is the PROBLEM
*/
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n = Asker();
int r = Remainder(n, 2);
if (r == 1)
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
main();
return 0;
}
Suppose, when I enter 7, I know that, it checks upto 6, then it should crash!(due to x + 1 > n condition). I don't know how to return 0 when it fails the else condition...
To answer to your question "Whats wrong with my Prime number Checker?" a lot of things are wrong:
Don't call main() in main. That's not how you do recursion
int Remainder(int n, int x) and you call it with a float (cast is missing) then with a bool : Remainder(n, x + 1 > n);
Your asker doesn't need to be a float
About the recursion within main there is two reason:
With this config you'll get an endless loop;
ISO C++ forbids taking address of function '::main'
//#include "stdafx.h" //This is an invalid header.
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0 && n>2 )//'2' have to be excluded.
//otherwise 2%2==0 can set
//'2' as a non prime which is wrong
return 1;
else if(x+1<n)
Remainder(n, x + 1);
/*
Here was the PROBLEM
Remainder(n, x + 1 > n) 'x + 1 > n ' is an invalid paramrter.
*/
else
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n=Asker();
int r=1; //It is essential to initialize r to 1
if(n!=1) //Have to exclude '1'. Otherwise
//It will assign '1' as prime which is wrong
r = Remainder(n, 2);
if (r == 1 )
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
//main(); //Why are you calling main again?
return 0;
}
Your first error was " #include "stdafx.h" ". Where'd you get this header?
Then inside int Remainder(int n, int x) function you used recursion and sent an invalid syntax " Remainder(n, x + 1 > n) ". You can't use syntax like x+1>n in a parameter.
After that why are you calling main() inside main function?
And your algorithm needed some touch which I have added and explained in comment.
But you should know that the shortest way to check a prime number is to check n%x==0 till x<=square_root(n).
First of all you don't have to check modulo for all numbers up to n-1: it is sufficient to check modulo up to sqrt(n). Second, you should return 0 from the function if the next divisor to check is larger than sqrt(n). Here is the corrected Remainder function.
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
{
if(x+1 > std::sqrt(n)) return 0;
else return Remainder(n, x + 1);
}
}
Finally, it is better to change the type of n in main and Asker from float to int, and return type of Asker should be int too.
This is not an exhausting list of what's wrong with the prime number checker in focus - just a way to fix it quickly. Essentially, such prime number checker shouldn't use recursion - it's more neat to just iterate over all potential divisors from 2 to sqrt(n).
I am writing a program to find the factorial of a user inputted number. My program works from, except for finding the factorial of 0. The requirement is that the factorial of 0 should output one, but I cannot think of a way to write this capability into the code without creating a special case for when 0 is entered. This is what I have so far
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int startingNumber = 0;
double factorialize = NULL;
while(startingNumber != -1) {
cout << "Enter the numbr to factorial: ";
cin >> startingNumber;
factorialize = startingNumber;
for(int x=startingNumber-1;x>=1;x--) {
factorialize = factorialize*x;
}
cout << factorialize << endl;
factorialize = NULL;
}
return 0;
}
This outputs a factorial accurately for all cases except 0. Is there a way to do this that doesn't require a special case? I am thinking no because when I read about the reasons for why 0! is 1, it says that it is defined that way, in other words, you cannot reason your way into why it is 1. Just like x^0, 0! = 1 has a different logic as to why than why 2^2 is 4 or 2! = 2.
try this:
factorialize = 1;
for(int x=2; x<=startingNumber;x++)
factorialize *= x;
Try this:
for (unsigned int n; std::cin >> n; )
{
unsigned int result = 1;
for (unsigned int i = 1; i <= n; ++i) { result *= i; }
std::cout << n << "! = " << result << "\n";
}
You can change the result type a bit (unsigned long long int or double or long double), but ultimately you won't be able to compute a large number of factorials in hardware.
First of all I do not see how it can be calculated accurately, as you multiply startingNumber twice. So just fix the logic with:
factorialize = 1.0;
for(int x=startingNumber;x>=1;x--) {
factorialize = factorialize*x;
}
And it should calculate factorial properly as well as handling 0 the proper way.
Also you should not use NULL as initial value for double, it is for pointers.
There is a complete factorial of number program of C++ which includes the facility of factorial of positive number,negative and zero.
#include<iostream>
using namespace std;
int main()
{
int number,factorial=1;
cout<<"Enter Number to find its Factorial: ";
cin>>number;
if(number<0
)
{
cout<<"Not Defined.";
}
else if (number==0)
{
cout<<"The Facorial of 0 is 1.";
}
else
{
for(int i=1;i<=number;i++)
{
factorial=factorial*i;
}
cout<<"The Facorial of "<<number<<" is "<<factorial<<endl;
}
return 0;
}
You can read full program logic on http://www.cppbeginner.com/numbers/how-to-find-factorial-of-number-in-cpp/
The function listed below returns the factorial FASTER than any solution posted here to this date:
const unsigned int factorial(const unsigned int n)
{
unsigned int const f[13] = { 1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600 };
return f[n];
}
I looks silly but it works for all factorials that fit into a 32-bit unsigned integer.
I have to make a program, which takes in a number and outputs the square root of it. Ex - 45 --> 3√5. I made a program, but it just returns the same number that i put in. Help would be greatly appreciated.
Here's my code -->
#include<iostream>
using namespace std;
int squarerootfinder(int number, int divisor){
if(divisor == 1){
return 1;
}
else{
if((number / (divisor * divisor))% 1 != 0){
divisor = squarerootfinder(number, divisor - 1);
}
if((number/ (divisor * divisor)) % 1 == 0 ){
return divisor;
}
}
}
int main(){
int number;
cout << "Enter a number to find the square root of it \n";
cin >> number;
int divisor = number;
int squareroot;
squareroot = squarerootfinder(number, divisor);
cout << squareroot << endl;
return 0;
}
Two problems with this line both related to the integer type:
if((number / (divisor * divisor))% 1 != 0){
Remembering that the result of an integer operation is an integer, what is the value of the first set of values that go into the function? Assume number is 5. Then we have:
5/(5*5) = 5/25 = 0
The same thing applies with the % 1. ints are always whole numbers, so modding by 1 always returns 0.
The issue here is to use the right algorithm, and that is you needed to use the cmath header in std library, in your squareRootFinder function. You can also use a function to get your integer. Here is my code. Hope it helps.
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int getPositiveInt(string rqstNum)
{
int num;
do
{
cout << rqstNum << endl;
cin >> num;
}while(num == 0);
return num;
}
double squareRootFinder(double Num)
{
double squareroot;
squareroot = sqrt(Num);
return squareroot;
}
int main()
{
int Num = getPositiveInt("Enter a number and i'll calculate the squareroot ");
double squareroot = squareRootFinder(Num);
// To dispay the answer to two decimal places we cast the squareroot variable
squareroot *= 100;
squareroot = (double)((int)squareroot);
squareroot /= 100;
cout << squareroot << endl;
return 0;
}