I'm trying to check if a number is a palindrome. I have written the code to check if a string is a palindrome using recursion, but I'm having a hard time writing the one to check for numbers.
I'm passing just the number to the method, nothing else (eg, number of digits).
Anyone got any suggestions for me?
You can convert your number to a string and pass the string to your already existing function you have written to test if a string is a palindrome.
You convert a number to a string using STR(NUMBER_HERE)
Why do you have to do it with recursion?
Here's what I would do (in pseudocode):
Set var to middle digit place if size is odd, otherwise, half of size if even (e.g. 3 if the number has 5 digits, 2 if it's 4).
Loop:
if odd, we skip the middle digit
for (i = 0; i < digitsArray.size /2; i++){
if (digitsArray[n-i]!=digitsArray[n+i])
break;
Then if we popped out before the end, it failed.
Something like that.
Related
Im new so if this question was already Asked (i didnt find it scrolling through the list of results though) please send me the link.
I got a math quiz and im to lazy to go through all the possibilities so i thought i can find a program instead. I know a bit about programming but not much.
Is it possible (and in what programming language, and how) to read only one digit, e.g at the 3rd Position, in a integer?
And how is an integer actually saved, in a kind of array?
Thanks!
You can get rid of any lower valued digit (the ones and tens if you only want the hundreds) by dividing with rounding/truncation. 1234/100 is 12 in most languages if you are doing integer division.
You can get rid of any higher valued digits by using taking the modulus. 12 % 10 is 2 in many languages; just find out how the modulus is done in yours. I use "modulus" meaning "divide and keep the rest only", i.e. it is the opposite of "divide with rounding"; that which is lost by rounding is the final result of the modulus.
The alternative is however to actually NOT see the input as a number and treat it as text. That way it is often easier to ignore the last 2 characters and all leading characters.
If the input is a number, how can I write a procedure that checks every digit and produces an output equal to the number of odd digits in this number?
I'm thinking about turning the number into a list first, but I'm trying to think of an easier solution.
Also, we're not allowed to use "odd?". So instead of using "odd?" to check whether or not a digit is odd, we can use "quotient"
Rather than convert to a string like in marekful's comment, try recursively taking off the most significant digit at a time using the mod operation. Then, you can use the quotient function to test for odd or even.
I'm using a certain electronic currency and they use pass phrases as passwords.
Basically every password is 12 English words long. How can I calculate how secure this is?
I don't know much about these things, but 12 words seem rather feasible with a dictionary attack (at least in my mind).
Naturally I'm worried how secure this is so instead of just asking if it is, I'd like to know methods on calculating it myself (you can spoil the answer, of course).
Any advice, links, literature recommendations, etc are welcome!
PS: How long it would take for an average computer to get an valid pass phrase with the details I gave above? I need to know if I have to keep making new accounts regularly to transfer funds to if it really doesn't take that much effort. I'd also appreciate any information on how to calculate that as well, but is not the main issue here. Thanks again!
It's all a question of entropy. How many different symbols are there to test ?
Traditionally, passwords are a string of characters. Symbols are then characters. If you use lower case letters only a-z is a range of 26 possible letters. With upper case and numbers, you get 62 symbols. With all special symbols that are in the ASCII set (so without fancy encodings) you get over 90 possible symbols already. In your case, a symbol is a word.
From this question on Oxford dictionaries’ website I would gather there are 115000 words that you could expect (without obsolete and derivatives).
To compute the number of combinations, you have to realize that for each possible symbol at a given position, you have the choice of every possible character at another position. With strings of characters, if your password starts with a $, you still have any character for the other positions. This means that we have to multiply the number of possible symbols for each symbol position. Thus with 2 characters that have s possible symbols, you have s*s possibilities. In general, you would have for c characters sc possibilities for a password.
Note that this means that in the case of dictionary words, you put random words instead of making sentences !
In your case, there are 11500012 possibilities, which is about 5.3*1060. So a huge lot.
The time to brute-force a password is then given by how much time t it takes to test a password, and the number of attempts, in your case t × 2.65 × 10^60 if you enumerate all combinations in a random order, and t × 5.3 × 10^60 if you try word combinations completely at random.
Here i have created the function on react-js to calculate the strenght of the password on the basic of some condition ..
A password must contain ATLEAST one Uppercase
A password must contain ATLEAST one lowercase
A password must contain ATLEAST one specialchar
A password must contain ATLEAST one Number
lenght of password must be 8 or above
export const PasswordStrenght: any = (password: string) => {
// Initial Percentage
let percentage: number = 0;
// Special character regex enter code here
const specialChars = /[ `!##$%^&*()_+\-=\[\]{};':"\\|,.\/?~]/;
const ownWeight : number = 20;
// Atleat one number
if (/\d/.test(password)) {
percentage = percentage + ownWeight;
}
// Atleat one lowercase alphabet
if (/.*[a-z].*/.test(password)) {
percentage = percentage + ownWeight;
}
// Atleat one uppercase alphabet
if (/.*[A-Z].*/.test(password)) {
percentage = percentage + ownWeight;
}
// Atleat one special character
if (specialChars.test(password)) {
percentage = percentage + ownWeight;
}
// lenght altest 8 or above
if (password.length >= 8) {
percentage = percentage + ownWeight;
}
return percentage;
};
my problem why my program takes much large time to execute, this program is supposed to check the user password, the approach used is
take password form console in to array and
compare it with previously saved password
comparision is done by function str_cmp()-returns zero if strings are equal,non zero if not equal
#include<stdio.h>
char str_cmp(char *,char *);
int main(void)
{
int i=0;
char c,cmp[10],org[10]="0123456789";
printf("\nEnter your account password\ntype 0123456789\n");
for(i=0;(c=getchar())!=EOF;i++)
cmp[i]=c;
if(!str_cmp(org,cmp))
{
printf("\nLogin Sucessful");
}
else
printf("\nIncorrect Password");
return 0;
}
char str_cmp(char *porg,char *pcmp)
{
int i=0,l=0;
for(i=0;*porg+i;i++)
{
if(!(*porg+i==*pcmp+i))
{
l++;
}
}
return l;
}
There are libraries available to do this much more simply but I will assume that this is an assignment and either way it is a good learning experience. I think the problem is in your for loop in the str_cmp function. The condition you are using is "*porg+i". This is not really doing a comparison. What the compiler is going to do is go until the expression is equal to 0. That will happen once i is so large that *porg+i is larger than what an "int" can store and it gets reset to 0 (this is called overflowing the variable).
Instead, you should pass a size into the str_cmp function corresponding to the length of the strings. In the for loop condition you should make sure that i < str_size.
However, there is a build in strncmp function (http://www.elook.org/programming/c/strncmp.html) that does this exact thing.
You also have a different problem. You are doing pointer addition like so:
*porg+i
This is going to take the value of the first element of the array and add i to it. Instead you want to do:
*(porg+i)
That will add to the pointer and then dereference it to get the value.
To clarify more fully with the comparison because this is a very important concept for pointers. porg is defined as a char*. This means that you have a variable that has the memory address of a 'char'. When you use the dereference operator (*, for example *porg) on the variable, it returns the value at stored in that piece of memory. However, you can add a number to the memory location to move to a different memory location. porg + 1 is going to return the memory location after porg. Therefore, when you do *porg + 1 you are getting the value at the memory address and adding 1 to it. On the other hand, when you do *(porg + 1) you are getting the value at the memory address one after where porg is pointing to. This is useful for arrays because arrays are store their values one after another. However, a more understandable notation for doing this is: porg[1]. This says "get the value 1 after the beginning of the array" or in other words "get the second element of the array".
All conditions in C are checking if the value is zero or non-zero. Zero means false, and every other value means true. When you use this expression (*porg + 1) for a condition it is going to do the calculation (value at porg + 1) and check if it is zero or not.
This leads me to the other very important concept for programming in C. An int can only hold values up to a certain size. If the variable is added to enough where it is larger than that maximum value, it will cycle around to 0. So lets say the maximum value of an int is 256 (it is in fact much larger). If you have an int that has the value of 256 and add 1 to it, it will become zero instead of 257. In reality the maximum number is 65,536 for most compilers so this is why it is taking so long. It is waiting until *porg + i is greater than 65,536 so that it becomes zero again.
Try including string.h:
#include <string.h>
Then use the built-in strcmp() function. The existing string functions have already been written to be as fast as possible in most situations.
Also, I think your for statement is messed up:
for(i=0;*porg+i;i++)
That's going to dereference the pointer, then add i to it. I'm surprised the for loop ever exits.
If you change it to this, it should work:
for(i=0;porg[i];i++)
Your original string is also one longer than you think it is. You allocate 10 bytes, but it's actually 11 bytes long. A string (in quotes) is always ended with a null character. You need to declare 11 bytes for your char array.
Another issue:
if(!(*porg+i==*pcmp+i))
should be changed to
if(!(porg[i]==pcmp[i]))
For the same reasons listed above.
So I'm just going to dive into this issue... I've got a heavily used web application that, for the first time in 2 years, failed doing an equality check on two doubles using the equality function a colleague said he'd also been using for years.
The goal of the function I'm about to paste in here is to compare two double values to 4 digits of precision and return the comparison results. For the sake of illustration, my values are:
Dim double1 As Double = 0.14625000000000002 ' The result of a calculation
Dim double2 As Double = 0.14625 ' A value that was looked up in a DB
If I pass them into this function:
Public Shared Function AreEqual(ByVal double1 As Double, ByVal double2 As Double) As Boolean
Return (CType(double1 * 10000, Long) = CType(double2 * 10000, Long))
End Function
the comparison fails. After the multiplication and cast to Long, the comparison ends up being:
Return 1463 = 1462
I'm kind of answering my own question here, but I can see that double1 is within the precision of a double (17 digits) and the cast is working correctly.
My first real question is: If I change the line above to the following, why does it work correctly (returns True)?
Return (CType(CType(double1, Decimal) * 10000, Long) = _
CType(CType(double2, Decimal) * 10000, Long))
Doesn't Decimal have even more precision, thus the cast to Long should still be 1463, and the comparison return False? I think I'm having a brain fart on this stuff...
Secondly, if one were to change this function to make the comparison I'm looking for more accurate or less error prone, would you recommend changing it to something much simpler? For example:
Return (Math.Abs(double1 - double2) < 0.0001)
Would I be crazy to try something like:
Return (double1.ToString("N5").Equals(double2.ToString("N5")))
(I would never do the above, I'm just curious about your reactions. It would be horribly inefficient in my application.)
Anyway, if someone could shed some light on the difference I'm seeing between casting Doubles and Decimals to Long, that would be great.
Thanks!
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Relying on a cast in this situation is error prone, as you have discovered - depending upon the rules used when casting, you may not get the number you expect.
I would strongly advise you to write the comparison code without a cast. Your Math.Abs line is perfectly fine.
Regarding your first question:
My first real question is: If I change
the line above to the following, why
does it work correctly (returns True)?
The reason is that the cast from Double to Decimal is losing precision, resulting in a comparison of 0.1425 to 0.1425.
When you use CType, you're telling your program "I don't care how you round the numbers; just make sure the result is this other type". That's not exactly what you want to say to your program when comparing numbers.
Comparing floating-point numbers is a pain and I wouldn't ever trust a Round function in any language unless you know exactly how it behaves (e.g. sometimes it rounds .5 up and sometimes down, depending on the previous number...it's a mess).
In .NET, I might actually use Math.Truncate() after multiplying out my double value. So, Math.Truncate(.14625 * 10000) (which is Math.Truncate(1462.5)) is going to equal 1462 because it gets rid of all decimal values. Using Truncate() with the data from your example, both values would end up being equal because 1) they remain doubles and 2) you made sure the decimal was removed from each.
I actually don't think String comparison is very bad in this situation since floating point comparison is pretty nasty in itself. Granted, if you're comparing numbers, it's probably better to stick with numeric types, but using string comparison is another option.