How can I generate all perfect numbers between 1 and 100?
A perfect number is a positive integer that is equal to the sum of its proper divisors. For example, 6(=1+2+3) is a perfect number.
So I suspect Frank is looking for an answer in Prolog, and yes it does smell rather homeworky...
For fun I decided to write up my answer. It took me about 50 lines.
So here is the outline of what my predicates look like. Maybe it will help get you thinking the Prolog way.
is_divisor(+Num,+Factor)
divisors(+Num,-Factors)
divisors(+Num,+N,-Factors)
sum(+List,-Total)
sum(+List,+Sofar,-Total)
is_perfect(+N)
perfect(+N,-List)
The + and - are not really part of the parameter names. They are a documentation clue about what the author expects to be instantiated.(NB) "+Foo" means you expect Foo to have a value when the predicate is called. "-Foo" means you expect to Foo to be a variable when the predicate is called, and give it a value by the time it finishes. (kind of like input and output, if it helps to think that way)
Whenever you see a pair of predicates like sum/2 and sum/3, odds are the sum/2 one is like a wrapper to the sum/3 one which is doing something like an accumulator.
I didn't bother to make it print them out nicely. You can just query it directly in the Prolog command line:
?- perfect(100,L).
L = [28, 6] ;
fail.
Another thing that might be helpful, that I find with Prolog predicates, is that there are generally two kinds. One is one that simply checks if something is true. For this kind of predicate, you want everything else to fail. These don't tend to need to be recursive.
Others will want to go through a range (of numbers or a list) and always return a result, even if it is 0 or []. For these types of predicates you need to use recursion and think about your base case.
HTH.
NB: This is called "mode", and you can actually specify them and the compiler/interpreter will enforce them, but I personally just use them in documentation. Also tried to find a page with info about Prolog mode, but I can't find a good link. :(
I'm not sure if this is what you were looking for, but you could always just print out "6, 28"...
Well looks like you need to loop up until n/2 that is 1/2 of n. Divide the number and if there is no remainder then you can include it in the total, once you have exhausted 1/2 of n then you check if your total added = the number you are testing.
For instance:
#include "stdafx.h"
#include "iostream"
#include "math.h"
using namespace std;
int main(void)
{
int total=0;
for(int i = 1; i<=100; i++)
{
for( int j=1; j<=i/2; j++)
{
if (!(i%j))
{
total+=j;
}
}
if (i==total)
{
cout << i << " is perfect";
}
//it works
total=0;
}
return 0;
}
Related
I know exactly how does a single modulus work. Does double modulus work the same? And assuming we have this pseudocode
j<-0
n<-10
for(j in 1:n)
{ if(!j%%2)
{
next
}
print(j)
}
What does the 'if' condition mean and what is the output of this code?
My solution is: If J is not divisible by 2 increase J, Otherwise, print J. And the overall code outputs even numbers from (1-10). Is this solution correct?
The %% operators is, as far as I know, not "standard" enough to be able to use it unambiguously in pseudocode without accompanying explanation of what it is supposed to be.
This snippet appears to be R code though, and in R the %% operator does mean remainder (with the sign of the divisor).
But since there is a ! (logical-not) too, the code will be printing odd numbers, since it's skipping the even numbers.
in an interview question, I got asked the following:
What is the purpose of the below method, and how can we rewrite it?
public int question_1(int a, int b)
{
while (a > b)
{
a -= b;
}
return a;
}
at first I thought it is equivalent to a%b, but it is not since it is "while (a > b)" and not "while ( a >= b)".
Thanks
Honestly, it's impossible to know the purpose of a method just by reading its implementation, even if we assume that it's bug-free.
But, we can start by documenting its behaviors:
If b is positive:
If a is positive, the method returns the least positive integer that is congruent to a modulo b. (For example, given 15 and 10, it will return 5; given 30 and 10, it will return 10.)
Otherwise, the method returns a.
If b is zero:
If a is positive, the method loops forever.
Otherwise, the method returns a.
If b is negative:
If a ≤ b, the method returns a.
Otherwise, the method's behavior depends on the language, since it will increase a until it's no longer greater than b. If the language defines integer arithmetic using "wraparound" rules, then the method will loop for a long time, then finally return a very negative number (unless b is itself very negative, in which case, depending on the value of a, the function might loop forever).
and given these, we can infer that the behaviors with zero and negative numbers are bizarre enough that the method is probably actually only intended to be used with positive numbers. So its behavior can be summarized as:
If a and b are both positive, then the method returns the least positive integer that is congruent to a modulo b.
If the above inference is correct, then the method can be rewritten as:
public int question_1(int a, int b) {
if (a <= 0 || b <= 0)
throw new IllegalArgumentException();
return (a - 1) % b + 1;
}
I would guess that its purpose is to compute a%b for positive ints, and that it has a bug.
If I saw this in production, I would have to check the uses of this function to see if question_1(n,n) == n is really correct. If so, I'd add a comment indicating why that is so. Otherwise I'd fix it.
It either case, it could be rewritten to use the % operator instead of a loop. If it's correct, it could be rewritten like this:
public int question_1(int a, int b)
{
if (a>b)
{
a = ((a-1)%b) + 1;
}
return a;
}
This is not the same in its handling of negative numbers, though, so again you'd have to check to make sure that's OK.
The reason I provide this answer when #ruakh has already provided such a carefully considered answer is that this is an interview question, so it's best if you take the opportunity to show how you would approach a problem like this on the job.
You don't really want to give the impression that you would spend a long time and a lot of effort thinking carefully about such a simple problem -- if you have to spend that much effort to solve a simple problem, imagine what you would spend on a big one!
At the same time, you want to demonstrate that you recognize the possible bug, and take the initiative to fix it or to spare future engineers the same task.
Ok, so still getting use to the basics with processing, and I am unsure if this is the correct way to do multiple arithmetic expressions with the same data, should I be typing each as its own code, or doing it like this?
here is the question;
Write the statements which perform the following arithmetic operations (note: the variable names can be changed). (i) a=50 b=60
c=43 result1 = a+b+c result2=a*b result3 = a/b
here is my code;
short a = 50;
short b = 60;
short c = 43;
int sum = a+b+c; // Subsection i
print (sum);
int sum2 = a*b; // Subsection ii
print (sum2);
int sum3 =a/b; // Subsection iii
print (sum3);
Using the same variable for a in all three expressions, like you're doing, is the right way. This means that if you wanted to change a, b, or c you'd only have to change it in one place.
You didn't mention what language, but there are a couple problems. It's hard to say what your knowledge level is, so I apologize in advance if this is beyond the scope of the assignment.
First, your variables are defined as short but they end up being assigned to int variables. That's implicit typecasting. Granted, short is basically a subset of int in most languages, but you should be aware that you're doing it and implicit typecasting can cause problems. It's slightly bad practice.
Second, your variable names are all called sumX but only one is a sum. That's definitely bad practice. Variable names should be meaningful and represent what they actually are.
Third, your division is dividing two integers and storing the result into an integer. This means that if you're using a strongly typed language you will be truncating the fractional portion of the quotient. You will get 0 as your output: 50 / 60 = 0.8333[...] which when converted to an integer truncates to 0. You may wish to consider using double or float as your data types if your answer is supposed to be accurate.
I am given a string and i need to find all possible letter combinations of this string. What is the best way I can achieve this?
example:
abc
result:
abc
acb
bca
bac
cab
cba
i have nothing so far. i am not asking for code. i am just asking for the best way to do it? an algorithm? a pseudocode? maybe a discussion?
you can sort it then use std::next_permutation
take a look at the example: http://www.cplusplus.com/reference/algorithm/next_permutation/
Do you want combinations or permutations? For example, if your string is "abbc" do you want to see "bbac" once or twice?
If you actually want permutations you can use std::next_permutation and it'll take care of all the work for you.
If you want the combinations (order independant) You can use a combination finding algorithm such as that found either here or here. Alternatively, you can use this (a java implementation of a combination generator, with an example demonstrating what you want.
Alternatively, if you want what you have listed in your post (the permutations), then you can (for C++) use std::next_permutation found in <algorithm.h>. You can find more information on std::next_permutation here.
Hope this helps. :)
In C++, std::next_permutation:
std::string s = "abc";
do
{
std::cout << s << std::endl;
} while (std::next_permutation(s.begin(), s.end()));
Copied from an old Wikipedia article;
For every number k, with 0 ≤ k < n!, the following algorithm generates a unique permutation on sequence s.
function permutation(k, s) {
for j = 2 to length(s) {
swap s[(k mod j) + 1] with s[j]; // note that our array is indexed starting at 1
k := k / j; // integer division cuts off the remainder
}
return s;
}
I have a large set (100k) of short strings (not more than 100 chars) and I need to quickly find all those who have a certain substring.
This will be used as a search box where the user starts typing and the system immediately gives "suggestions" (the strings that have as a substring the text that the user typed). Something similar to the "Tag" box in StackOverflow.
As this will be interactive, it should be pretty fast. What algorithm or data structure do you recommend for this?
BTW, I'll be using Delphi 2007.
Thanks in advance.
I wrote out a long blurb, doing a bunch of complexity calculations and xzibit jokes (tree in a tree so you can lookup when you lookup), but then realized that this is easier than I thought. Browsers do this all the time and they never precompute big tables every time you're loading a page.
http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm
what it means is that you take your 100k strings and combine them into one long string. you then take your query substring, and iterate over your big string, looking for your matches. but you're not jumping by character (which would mean you're looking at 100k*100 iterations). you're jumping by the length of your substring, so the longer your substring gets, the faster this goes.
here's a great example: http://userweb.cs.utexas.edu/users/moore/best-ideas/string-searching/fstrpos-example.html
they're searching for the string EXAMPLE.
this is the kind of stuff browsers and text editors do, and they dont really build giant prefix tables every time you load a page.
The data structure you'll likely want to use is a Trie, specifically a suffix trie. Read this article for a good explanation of how they work and how to write one for your problem.
While you certainly can speed things up with a better data structure, this is a time that brute force might be perfectly adequate. Doing a quick test:
[Edit: changed code to search for substrings, edited again to shorten the substring it searches for compared to the ones it searches in.]
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <time.h>
std::string rand_string(int min=20, int max=100) {
size_t length = rand()% (max-min) + min;
std::string ret;
for (size_t i=0; i<length; i++)
ret.push_back(rand() % ('z' - 'a') + 'a');
return ret;
}
class substr {
std::string seek;
public:
substr(std::string x) : seek(x) {}
bool operator()(std::string const &y) { return y.find(seek) != std::string::npos; }
};
int main() {
std::vector<std::string> values;
for (int i=0; i<100000; i++)
values.push_back(rand_string());
std::string seek = rand_string(5, 10);
const int reps = 10;
clock_t start = clock();
std::vector<std::string>::iterator pos;
for (int i=0; i<reps; i++)
pos = std::find_if(values.begin(), values.end(), substr(seek));
clock_t stop = clock();
std::cout << "Search took: " << double(stop-start)/CLOCKS_PER_SEC/reps << " seconds\n";
if (pos == values.end())
std::cout << "Value wasn't found\n";
else
std::cout << "Value was found\n";
return 0;
}
On my machine (around 4 years old -- hardly a speed demon by current standards) this runs in around 3 10 milliseconds per search. That's fast enough to appear instantaneous to an interactive user -- and with 10 times as many strings, it would still be fine.
I hate to disagree with Mike and his supporters, but suffix trees (data structure described in his link) are a lot of pain to implement. And finding reliable implementation in Pascal/Delphi might be difficult too.
Suffix Arrays offer the same functionality while being a lot simpler. The tradeoff is O(m * logn) complexity, where m is length of the search token and n is size of the dataset (100kb in this case).
In case somebody doesn't know, both suffix trees and suffix arrays allow you to find all occurrences of substring s in long text t.
Fernando's problem can be reduced to this one, by concatenating initial set of strings into one string using some delimiter symbol. For example, is initial set is ["text1", "text2", "some text"], then result string t will be "text1|text2|some text".
Now, instead of searching for string "text" in each word separately, we just need to find all occurrences of it in big string t.
I also recommend Oren's answer where he suggests another realistic approach.
This Delphi implementation of Boyer-Moore-Horspool might give you what you need.
Disclaimer: I did not try this code...
What you're probably looking for is an n-gram. It's used to find the most likely words related to your substring. Very interesting stuff, and though it may be overkill for what you're looking for, it's still good to know.