Is there any predefined function in c++ to check whether the number is square of any number and same for the cube..
No, but it's easy to write one:
bool is_perfect_square(int n) {
if (n < 0)
return false;
int root(round(sqrt(n)));
return n == root * root;
}
bool is_perfect_cube(int n) {
int root(round(cbrt(n)));
return n == root * root * root;
}
sqrt(x), or in general, pow(x, 1./2) or pow(x, 1./3)
For example:
int n = 9;
int a = (int) sqrt((double) n);
if(a * a == n || (a+1) * (a+1) == n) // in case of an off-by-one float error
cout << "It's a square!\n";
Edit: or in general:
bool is_nth_power(int a, int n) {
if(n <= 0)
return false;
if(a < 0 && n % 2 == 0)
return false;
a = abs(a);
int b = pow(a, 1. / n);
return pow((double) b, n) == a || pow((double) (b+1), n) == a;
}
No, there are no standard c or c++ functions to check whether an integer is a perfect square or a perfect cube.
If you want it to be fast and avoid using the float/double routines mentioned in most of the answers, then code a binary search using only integers. If you can find an n with n^2 < m < (n+1)^2, then m is not a perfect square. If m is a perfect square, then you'll find an n with n^2=m. The problem is discussed here
Try this:
#include<math.h>
int isperfect(long n)
{
double xp=sqrt((double)n);
if(n==(xp*xp))
return 1;
else
return 0;
}
The most efficient answer could be this
int x=sqrt(num)
if(sqrt(num)>x){
Then its not a square root}
else{it is a perfect square}
This method works because of the fact that x is an int and it will drop down the decimal part to store only the integer part. If a number is perfect square of an integer, its square root will be an integer and hence x and sqrt(x) will be equal.
For identifying squares i tried this algorithm in java. With little syntax difference you can do it in c++ too.
The logic is, the difference between every two consecutive perfect squares goes on increasing by 2. Diff(1,4)=3 , Diff(4,9)=5 , Diff(9,16)= 7 , Diff(16,25)= 9..... goes on.
We can use this phenomenon to identify the perfect squares.
Java code is,
boolean isSquare(int num){
int initdiff = 3;
int squarenum = 1;
boolean flag = false;
boolean square = false;
while(flag != true){
if(squarenum == num){
flag = true;
square = true;
}else{
square = false;
}
if(squarenum > num){
flag = true;
}
squarenum = squarenum + initdiff;
initdiff = initdiff + 2;
}
return square;
}
To make the identification of squares faster we can use another phenomenon, the recursive sum of digits of perfect squares is always 1,4,7 or 9.
So a much faster code can be...
int recursiveSum(int num){
int sum = 0;
while(num != 0){
sum = sum + num%10;
num = num/10;
}
if(sum/10 != 0){
return recursiveSum(sum);
}
else{
return sum;
}
}
boolean isSquare(int num){
int initdiff = 3;
int squarenum = 1;
boolean flag = false;
boolean square = false;
while(flag != true){
if(squarenum == num){
flag = true;
square = true;
}else{
square = false;
}
if(squarenum > num){
flag = true;
}
squarenum = squarenum + initdiff;
initdiff = initdiff + 2;
}
return square;
}
boolean isCompleteSquare(int a){
// System.out.println(recursiveSum(a));
if(recursiveSum(a)==1 || recursiveSum(a)==4 || recursiveSum(a)==7 || recursiveSum(a)==9){
if(isSquare(a)){
return true;
}else{
return false;
}
}else{
return false;
}
}
For perfect square you can also do:
if(sqrt(n)==floor(sqrt(n)))
return true;
else
return false;
For perfect cube you can:
if(cbrt(n)==floor(cbrt(n)))
return true;
else
return false;
Hope this helps.
We could use the builtin truc function -
#include <math.h>
// For perfect square
bool is_perfect_sq(double n) {
double r = sqrt(n);
return !(r - trunc(r));
}
// For perfect cube
bool is_perfect_cube(double n) {
double r = cbrt(n);
return !(r - trunc(r));
}
bool isSquare(int n) {
return floor(sqrt(n)) == ceil(sqrt(n));
}
bool isQube(int n) {
return floor(cbrt(n)) == ceil(cbrt(n));
}
Related
i need to determine if a number is palindrome or not
ex: 121 yes,
ex: -121 no.
the program seems to work with palindrome numbers however i am having trouble figuring out the negative numbers, and non palindrome numbers
class Solution {
public:
bool isPalindrome(int x) {
int reverse = 0;
int digit;
int n = x;
bool t = true;
while(x > 0){
digit = x%10;
reverse = (reverse*10) + digit;
x = x/10;
}
if (n == reverse) {
return t;
}
else if(n != reverse) {
return -1;
}
return -1;
}
};
bool isPalindrome(int A)
{
int Rev{ 0 } , rem , C{ A };
while( ( abs( A ) ) ! = 0 )
{
rem = ( abs( A ) ) % 10;
Rev = Rev * 10 + rem;
A / = 10;
}
if( C ! = Rev or C < 0)
return false;
else if( C == Rev and C > 0)
return true;
}
Change your if statements with the following and then this works for negative numbers.
Hope this works for you!!
class Solution {
public boolean isPalindrome(int x){
int reverse=0;
int duplicate_x=x;
for(int i=0;i<=x;i++)
{
int r=x%10;
reverse=(reverse*10)+r;
x=x/10;
}
if(x>=1){ **wrote this if condition to catch unit place number**
reverse=(reverse*10)+x;
}
if(reverse==duplicate_x)
{
return true;
}
else
{
return false;
}
}
}
I used for loop because I was getting time exceeding error in leetcode
and has you mention in your question about negative number palindrome I don't get it why should we write code for those negative number palindrome where we know a **negative number cannot be a palindrome number!
Please correct me if I am wrong
int x=121;
if(x<0){
System.out.println("false");
System.exit(0);
}
int div, sum=0;
int res=x;
while(x!=0){
div = x%10;
sum = sum*10 + div;
x=x/10;
}
if(sum==res)
System.out.println("True");
Can't be able to come up with a simple solution more than this one.
I am currently working on a program in C++, the ultimate goal of which is to display a list of prime factors for a given value, up to the limit of unsigned long int.
It takes advantage of trial division for the first 1000 prime numbers, and uses Fermat's Method of Factorisation for every value thereafter.
Generally, I'd say the program works okay for most numbers I've tested it with, including some larger numbers. However, I seem to have hit a snag with certain numbers. For example, when the prime number 18446744073709551557 is entered, it crashes entirely. For other larger values such as 246819835539726757, it displays the first five prime factors (7, 11, 37, 131, and 557) correctly, but miscalculates the last two, which should be 18379 and 64601.
The code for the function is as follows:
std::list < unsigned long int >primeFactors(unsigned long int n)
{
bool complete = false;
std::list<unsigned long int> factors;
unsigned long int ans1 = 0;
unsigned long int ans2 = 0;
int a;
int b;
// If n is 0 or 1, return a blank list
//
// This is run outside the while loop, as n will never be 0 or 1 after
// the initial calculation
if (n == 0 || n == 1)
{
complete = true;
return factors;
}
while (complete == false)
{
// if n is a prime number, add to the list and return
if (isPrime(n) == true)
{
factors.push_back(n);
complete = true;
return factors;
}
// if n is even (i.e. divisible by 2), add 2 and n/2 to the list and
// return
else if (divisibleByPrime(n) != 0)
{
unsigned long int divisor = divisibleByPrime(n);
ans1 = divisor;
ans2 = n / divisor;
if (isPrime(ans1) == true && isPrime(ans2) == true)
{
factors.push_back(ans1);
factors.push_back(ans2);
complete = true;
return factors;
}
else
{
if (isPrime(ans1) == true)
{
factors.push_back(ans1);
n = ans2;
}
else
{
factors.push_back(ans2);
n = ans1;
}
}
}
else
{
// a is the square root of n + a^2
unsigned long int i = 1;
float squareRoot;
std::stringstream ss;
std::string str;
bool isDouble = true;
bool answerFound = false;
unsigned long int x;
unsigned long int y;
while (answerFound == false)
{
isDouble = false;
squareRoot = (float)sqrt(n + (i * i));
ss << squareRoot;
str = ss.str();
for (char& i : str)
{
if (strchr(".", i) != NULL)
{
isDouble = true;
}
}
if (isDouble == true)
{
ss.str("");
i += 1;
}
else
{
answerFound = true;
}
}
x = (unsigned long int) squareRoot;
y = i;
ans1 = x + y;
ans2 = x - y;
if (isPrime(ans1) == true && isPrime(ans2) == true)
{
factors.push_back(ans1);
factors.push_back(ans2);
complete = true;
return factors;
}
else
{
if (isPrime(ans1))
{
factors.push_back(ans1);
n = ans2;
}
else
{
factors.push_back(ans2);
n = ans1;
}
}
}
}
I have not included functions such as isPrime or divisibleByPrime as both seem to work fine in an isolated environment.
EDIT: I appreciate certain variables are such are a little messy at the minute, but I plan on rectifying that soon.
My original function to determine if a number was prime was:
bool is_prime(int x) {
for (int y = 2; y < x; ++y) {
if (x % y == 0) {
return false;
}
}
return true;
}
This ran with a complexity of O(x) as you may have had to go to x.
I've learned of some optimizations and need a check on my big-o. Here is the improved program:
bool is_prime(int x)
{
if (x % 2 == 0 && x > 2) {
return false;
}
for (int y = 3; y*y <= x; y += 2) {
if (x % y == 0) {
return false;
}
}
return true;
}
Does the fact that I am now going up to the sqrt() change this to O(sqrt(x))?
Yes, but here are no ns. The complexity of your new function is O(sqrt(x)). When you say O(N) and don't specify what N is, it's generally taken to be the size of the input. This is confusing for functions that take a single number argument, so in those cases you should be explicit.
Absolutely,
The complexity of your new function is
O(sqrt(x))
But still, there is some room for optimization. Have a look at the code mentioned below:
bool isPrime(int n)
{
// Boundary cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n%2 == 0 || n%3 == 0) return false;
for (int i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
I am using a simple backtracking algorithm to find all the paths but it does not give the right answer. I am not able to figure out the mistake. We can move up, down, left and right from a given position.
Int path(int a[][200],int n,int m,int r,int c)
{
if(n == r - 1 && m == c-1) {
return 1;
}
else if(n >= r || m >= c || n < 0 || m < 0) {
return 0;
}
else if(vis[n][m] == 1) {
return 0;
}
else {
vis[n][m] = 1;
int x = path(a,n+1,m,r,c);
int y = path(a,n,m+1,r,c);
int u = path(a,n-1,m,r,c);
int v = path(a,n,m-1,r,c);
vis[n][m] = 0;
return (x+y+u+v);
}
}
To find the paths or count the paths are not exactly the same thing. I will assume you want to just count the paths (because the title of your question), and that you can only move right or move down.
For this you don't really need a matrix (representing the grid) as a parameter. The following is a simple (although not efficient) recursive solution that also will work for a n*m grid:
int countPaths(int m, int n) {
if (m == 0 || n == 0)
return 1;
return countPaths(m-1, n) + countPaths(m, n-1);
}
The mathematical solution for the general n*n grid is:
(2n choose n) = (2*n)!/(n!*n!)
Then, comparing results with the formula:
countPaths(1, 1) == 2 // (2*1)!/(1!*1!)=2
countPaths(2, 2) == 6 // (2*2)!/(2!*2!)=6
countPaths(3, 3) == 20 // (2*3)!/(3!*3!)=20
Your backtracking approach will give the same results, but with some considerations. For example, consider when n=2, you will need a 3x3 matrix (and in general a (n+1)x(n+1) matrix) to represent/explore (and mark with 1) all the paths for the 2x2 grid:
int countPaths(int a[][3],int n, int m, int r, int c) {
if(n == r-1 && m == c-1) {
return 1;
}
else if(n >= r || m >= c || n < 0 || m < 0) {
return 0;
}
else if(vis[n][m] == 1) {
return 0;
}
else {
vis[n][m] = 1;
int x = countPaths(a,n+1,m,r,c);
int y = countPaths(a,n,m+1,r,c);
vis[n][m] = 0;
return (x+y);
}
}
Then:
countPaths(vis, 0, 0, 3, 3) == 6 // (2*2)!/(2!*2!)=6
i have a problem on iterative function and recursive function.
i have a iterative function and i have to convert it into a recursive one.
could you give me some advice on my code?thanks so much
the code is to determine if the array of data points correspond to a concave function using recursion.
Here is the code of the iterative version:
bool isConcave(double a[], int n)
{
int slope = 1;
bool concave = true;
for (int i = 1; i < n && concave; i++)
{
double delta = a[i] - a[i-1];
if (slope > 0)
{
if (delta < 0)
slope = -1;
}
else if (delta > 0)
concave = false; // slope == -1 and delta > 0
}
return concave;
}
And, here is the code of my recursive version which can't work:
bool isConcave_r(double a[], int n, int& slope)
{
//Implement this function using recursion
double delta = a[n] - a[n-1];
bool concave = true;
if (n == 0)
return false;
if (slope > 0)
{
if (delta < 0)
{
slope = -1;
}
else
concave = true;
}else
return 0;
//dummy return statement
return isConcave_r(a, n, slope);
}
In the iterative version of your program, the computation moves from 1 to n-1, but in the recursive version computation moves form n-1 to 1. So, instead of tail recursion, use head recursion. And slope should be static variable. So, declare slope as static variable. It will work.
Not necessary the best/cleanest way, but you may replace any loop
for (int i = 0; i != N; ++i) {
body(i, localVars);
}
by
void body_rec(int N, int i, LocalVars& localVars)
{
if (i == N) return;
body(i, localvars);
body_rec(N, i + 1, localVars);
}
or
int body_rec(int N, int i, LocalVars& localVars)
{
if (i == N) return localVars.res; // or any correct value
body(i, localvars);
if (localVars.end) { // break the "loop", and so stop the recursion.
return localVars.res; // or any correct value
}
return body_rec(N, i + 1, localVars);
}
So, in your case, you forget to pass slope into the recursion.
[edit]
Full solution:
bool isConcave_r(int N, int i, double a[], int slope)
{
if (i >= N) return true;
const double delta = a[i] - a[i-1];
if (slope > 0) {
if (delta < 0) {
slope = -1;
}
}
else if (delta > 0) {
return false;
}
return isConcave_r(N, i + 1, a, slope);
}
bool isConcave(double a[], int n)
{
int i = 1;
int slope = 1;
return isConcave_r(n, i, a, slope);
}
Note also that the name seems "incorrect", you don't check if the "curve" is concave, case where delta == 0 should be specific I think...