Search Results

Search found 425 results on 17 pages for 'f prime'.

Page 6/17 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Java 8 Stream, getting head and tail

    - by lyomi
    Java 8 introduced a Stream class that resembles Scala's Stream, a powerful lazy construct using which it is possible to do something like this very concisely: def from(n: Int): Stream[Int] = n #:: from(n+1) def sieve(s: Stream[Int]): Stream[Int] = { s.head #:: sieve(s.tail filter (_ % s.head != 0)) } val primes = sieve(from(2)) primes takeWhile(_ < 1000) print // prints all primes less than 1000 I wondered if it is possible to do this in Java 8, so I wrote something like this: IntStream from(int n) { return IntStream.iterate(n, m -> m + 1); } IntStream sieve(IntStream s) { int head = s.findFirst().getAsInt(); return IntStream.concat(IntStream.of(head), sieve(s.skip(1).filter(n -> n % head != 0))); } IntStream primes = sieve(from(2)); PrimitiveIterator.OfInt it = primes.iterator(); for (int prime = it.nextInt(); prime < 1000; prime = it.nextInt()) { System.out.println(prime); } Fairly simple, but it produces java.lang.IllegalStateException: stream has already been operated upon or closed because both findFirst() and skip() is a terminal operation on Stream which can be done only once. I don't really have to use up the stream twice since all I need is the first number in the stream and the rest as another stream, i.e. equivalent of Scala's Stream.head and Stream.tail. Is there a method in Java 8 Stream that I can achieve this? Thanks.

    Read the article

  • Strange thread behavior in Perl

    - by Zaid
    Tom Christiansen's example code (à la perlthrtut) is a recursive, threaded implementation of finding and printing all prime numbers between 3 and 1000. Below is a mildly adapted version of the script #!/usr/bin/perl # adapted from prime-pthread, courtesy of Tom Christiansen use strict; use warnings; use threads; use Thread::Queue; sub check_prime { my ($upstream,$cur_prime) = @_; my $child; my $downstream = Thread::Queue->new; while (my $num = $upstream->dequeue) { next unless ($num % $cur_prime); if ($child) { $downstream->enqueue($num); } else { $child = threads->create(\&check_prime, $downstream, $num); if ($child) { print "This is thread ",$child->tid,". Found prime: $num\n"; } else { warn "Sorry. Ran out of threads.\n"; last; } } } if ($child) { $downstream->enqueue(undef); $child->join; } } my $stream = Thread::Queue->new(3..shift,undef); check_prime($stream,2); When run on my machine (under ActiveState & Win32), the code was capable of spawning only 118 threads (last prime number found: 653) before terminating with a 'Sorry. Ran out of threads' warning. In trying to figure out why I was limited to the number of threads I could create, I replaced the use threads; line with use threads (stack_size => 1);. The resultant code happily dealt with churning out 2000+ threads. Can anyone explain this behavior?

    Read the article

  • Runtime of optimized Primehunter

    - by Setton
    Ok so I need some serious runtime help here! This method should take in an int value, check its primality, and return true if the number is indeed a prime. I understand why the loop only needs to go up to i squared, I understand that the worst case scenario is the case in which either the number is prime (or a multiple of a prime). But I don't understand how to quantify the actual runtime. I have done the loop myself by hand to try to understand the pattern or correlation of the number (n) and how many loops occur, but I literally feel like I keep falling into the same trap every time. I need a new way of thinking about this! I have a hint: "Think about the SIZE of the integer" which makes me want to quantify the literal number of integers in a number in relation to how many iterations it does in the for loop (floor log(n)) +1). BUT IT'S NOT WORKIIIING?! I KNOW it isn't square root n, obviously. I'm asking for Big O notation. public class PrimeHunter { public static boolean isPrime(int n) { boolean answer = (n > 1) ? true : false; //runtime = linear runtime for (int i = 2; i * i <= n; i++) //runtime = ????? { if (n % i == 0) //doesn't occur if it is a prime { answer = false; break; } } return answer; //runtime = linear runtime } }

    Read the article

  • CodePlex Daily Summary for Sunday, June 03, 2012

    CodePlex Daily Summary for Sunday, June 03, 2012Popular ReleasesLiveChat Starter Kit: LCSK v1.5.2: New features: Visitor location (City - Country) from geo-location Pass configuration via javascript for the chat box New visitor identification (no more using the IP address as visitor identification) To update from 1.5.1 Run the /src/1.5.2-sql-updates.txt SQL script to update your database tables. If you have it installed via NuGet, simply update your package and the file will be included so you can run the update script. New installation The easiest way to add LCSK to your app is by...Prime Factorization: Prime Factorization V2: Download the installation package and run it, to install prime factorization on your computer.DNN Content Localization Tools: CLTools v0.4 (Beta4): 3th Beta release for DNN 6.1 and obove Bug corrections : - Copy module work againNTemplates: NTemplates full source code and examples: This release includes the following changes: - NTemplates code. More enhacements and bug fixing. Nested scans seems to be working ok now. New event: ScanStart. Very usuful for calculating totals (see the example) - Examples. 2 new examples on nested scans. One of them very simple I did just for debugging. The other one is a report of invoices grouped by vendor, including totals calculations. Planned Roadmap: - Work on fixing performance bottlenecek: Try to compile the expression...ZXMAK2: Version 2.6.2.3: - add support for ZIP files created on UNIX system; - improve WAV support (fixed PCM24, FLOAT32; added PCM32, FLOAT64); - fix drag-n-drop on modal dialogs; - tape AutoPlay feature (thanks to Woody for algorithm).Net Code Samples: Full WCF Duplex Service Example: Full WCF Duplex Service ExampleKendo UI ASP.NET Sample Applications: Sample Applications (2012-06-01): Sample application(s) demonstrating the use of Kendo UI in ASP.NET applications.Better Explorer: Better Explorer Beta 1: Finally, the first Beta is here! There were a lot of changes, including: Translations into 10 different languages (the translations are not complete and will be updated soon) Conditional Select new tools for managing archives Folder Tools tab new search bar and Search Tab new image editing tools update function many bug fixes, stability fixes, and memory leak fixes other new features as well! Please check it out and if there are any problems, let us know. :) Also, do not forge...myManga: myManga v1.0.0.3: Will include MangaPanda as a default option. ChangeLog Updating from Previous Version: Extract contents of Release - myManga v1.0.0.3.zip to previous version's folder. Replaces: myManga.exe BakaBox.dll CoreMangaClasses.dll Manga.dll Plugins/MangaReader.manga.dll Plugins/MangaFox.manga.dll Plugins/MangaHere.manga.dll Plugins/MangaPanda.manga.dllPlayer Framework by Microsoft: Player Framework for Windows 8 Metro (Preview 3): Player Framework for HTML/JavaScript and XAML/C# Metro Style Applications. Additional DownloadsIIS Smooth Streaming Client SDK for Windows 8 Microsoft PlayReady Client SDK for Metro Style Apps Release notes:Support for Windows 8 Release Preview (released 5/31/12) Advertising support (VAST, MAST, VPAID, & clips) Miscellaneous improvements and bug fixesMicrosoft Ajax Minifier: Microsoft Ajax Minifier 4.54: Fix for issue #18161: pretty-printing CSS @media rule throws an exception due to mismatched Indent/Unindent pair.Silverlight Toolkit: Silverlight 5 Toolkit Source - May 2012: Source code for December 2011 Silverlight 5 Toolkit release.Windows 8 Metro RSS Reader: RSS Reader release 6: Changed background and foreground colors Used VariableSizeGrid layout to wrap blog posts with images Sort items with Images first, text-only last Enabled Caching to improve navigation between framesJson.NET: Json.NET 4.5 Release 6: New feature - Added IgnoreDataMemberAttribute support New feature - Added GetResolvedPropertyName to DefaultContractResolver New feature - Added CheckAdditionalContent to JsonSerializer Change - Metro build now always uses late bound reflection Change - JsonTextReader no longer returns no content after consecutive underlying content read failures Fix - Fixed bad JSON in an array with error handling creating an infinite loop Fix - Fixed deserializing objects with a non-default cons...DotNetNuke® Community Edition CMS: 06.02.00: Major Highlights Fixed issue in the Site Settings when single quotes were being treated as escape characters Fixed issue loading the Mobile Premium Data after upgrading from CE to PE Fixed errors logged when updating folder provider settings Fixed the order of the mobile device capabilities in the Site Redirection Management UI The User Profile page was completely rebuilt. We needed User Profiles to have multiple child pages. This would allow for the most flexibility by still f...????: ????2.0.1: 1、?????。WiX Toolset: WiX v3.6 RC: WiX v3.6 RC (3.6.2928.0) provides feature complete Burn with VS11 support. For more information see Rob's blog post about the release: http://robmensching.com/blog/posts/2012/5/28/WiX-v3.6-Release-Candidate-availableJavascript .NET: Javascript .NET v0.7: SetParameter() reverts to its old behaviour of allowing JavaScript code to add new properties to wrapped C# objects. The behavior added briefly in 0.6 (throws an exception) can be had via the new SetParameterOptions.RejectUnknownProperties. TerminateExecution now uses its isolate to terminate the correct context automatically. Added support for converting all C# integral types, decimal and enums to JavaScript numbers. (Previously only the common types were handled properly.) Bug fixe...Phalanger - The PHP Language Compiler for the .NET Framework: 3.0 (May 2012): Fixes: unserialize() of negative float numbers fix pcre possesive quantifiers and character class containing ()[] array deserilization when the array contains a reference to ISerializable parsing lambda function fix round() reimplemented as it is in PHP to avoid .NET rounding errors filesize bypass for FileInfo.Length bug in Mono New features: Time zones reimplemented, uses Windows/Linux databaseSharePoint Euro 2012 - UEFA European Football Predictor: havivi.euro2012.wsp (1.1): New fetures:Admin enable / disable match Hide/Show Euro 2012 SharePoint lists (3 lists) Installing SharePoint Euro 2012 PredictorSharePoint Euro 2012 Predictor has been developed as a SharePoint Sandbox solution to support SharePoint Online (Office 365) Download the solution havivi.euro2012.wsp from the download page: Downloads Upload this solution to your Site Collection via the solutions area. Click on Activate to make the web parts in the solution available for use in the Site C...New ProjectsAFS.PhonePusherConnectorVX: pusher for phone vxApache: this is the Apache project.Apple: this is the Apple project.CUARTOAZZJL: HURRA!!Designing Windows 8 Applications with C# and XAML: This project hosts the source code used in the example projects for the book, Designing Windows 8 Metro Applications with C# and XAML.Easy Internet: CyberWeb ist ein einfacher Webbrowser für PC Neulinge. Ideal für Leute, die noch keine PC-Erfahrung haben.Easy Outlook Backup: Beschreibung: Easy Outlook Backup ist ein Programm das alle Daten von Outlook sichert. Ideal für Leute, die noch keine PC-Erfahrung haben. Easy Realtime Start: Beschreibung: Easy Realtime Start ist ein Programm das einen Prozess in höchster Priorität startet. Und das ganz bequem Per drag & drop. Ideal für Leute, die aufwendige Programme starten müssen. (zB.: “Blender” Free 3D Designer)eStock: eStock ist ein Verwaltungstool für Elektroniker um Bauteile im "Lager" sowie Projekte zu verwalten. Es bietet eine Möglichkeit festzulegen, um welche Art von Bauteil es sich handelt und wo sich dieses im Lager bzw. Regal befindet. Die Projektverwaltung ermöglicht es, Bauteile einem Projekt hinzuzufügen und eine Bestellliste / Einkaufsliste von Bauteilen, die nicht mehr im Lager vorhanden sind, zu erstellen. FuTTY: FireEgl's PuTTY -- FuTTY! FuTTY is a fork of PuTTY and PuTTYTray.GeometryWorld: To Do...Google: this is the Google project.Google Advance Search: An easy way to create documents search at Google and read your emails and Much moregoogle maps viewer for dynamics crm 2011: Easy google maps viewer for dynamics CRM 2011GPS Status - (GPS tool für GPS-Dongles und Mäuse) - GPS-Empfänger: Mein Programm verbindet sich mit dem externen GPS über einen Com-Port und bietet verschiedene Tools.Harmony Text Editor: Harmony is a ridiculously simple text editor for code and poetry.Hi! Football: .Goal / Objective -> To help friends gather for enjoying watching football together. .How it works -> To basically choose your favorite team, choose one of the matches fetched for his team, our app will generate a list of popular restraunts, cafes where he can watch the chosen match, the user can select one of the generated locations around his area, and create an event inviting his friends to join him and he can also join other friends' events.Java: this is the Java project.LevelUp Serializer: LevelUp Serializer is a small and simple serialize library.It can help developer to serialize and deserialize data more convenient. Feature: - Ease of use - Supports almost all serializer, like Binary、Xml、Soap、Json、DataContract. - Support serialize to file、serialize to stream、deserialize from file、deserialize from stream. - Support Xml encryption. - Support accelerated through the XML the serialization assemble.LFormatConvert: ????Linux???????????????????????,??ffmpeg????Machine QA Manager: Machine QA Manager is intended to save and help trend results from radiation therapy equipment testing. The program will be made as generic as possible from a initial setup to enable it's use for other types of routine testing activities (for example factory equipment) but preconfigured templates for radiation therapy will be supplied for the convenience of people working in that domain.maven-asbuild-plugin: maven-asbuild-plugin incorporates the adobe flash/flex based artifacts like swc or swf into the maven methology.Midnight Peach - C# framework generator for LINQ: C# framework generator for LINQMiku???????: ????????,????????!?????????????,??????????。?????????????????!MIKU????????????,??!????????????、????。 This program used to detect music beat.You can listen to music while press button,and it can display the BPM of the song.Miku will wave to you.MyTestingStudy: my personal testing studyNameless Sprite Editor: Nameless Sprite Editor is a tool used to thoroughly edit the graphics in ALL Game Boy Advance games. [ UNDER CONSTRUCTION ]NeoModulus Business Rules Builder: A windows form application that allows non-programmers to build strict definitions of a business domain. Once the definition is complete the program will build out object oriented C# files and a .net DLL. My test business domain is the open SRD, basically Dungeons and Dragons 3.5 edition.NodeJs: this is the NodeJs projectNoSQL: this is the Nosql project.OmniKassa for NopCommerce: OmniKassa payment module plugin for nopCommerceOn-Line Therapy: testOpen School: This project is about to create an open platform for all the academic institutions, so that they can manage all of their work. Our efforts will be for every kind of institution who are currently struggling with different kind of systems in place which are not collaborating with each other. This project will provide a common platform to all these kind of systems and provide them a better solution which actually works. Oracle: this is the Oracle project.Orchard Web Services: RESTful web services to expose interaction with Orchard content management.Personal Social Network using asp.net mvc and mongodb: FirstRooster is a network platform that let user create their own social network of interest to connect and share with like minded people anywhere.peshop: E-Commerce application , separated by DAl,BLL and Presentation layersPHP: this is the PHP project.Prime Factorization: Factoring trinomials using the ac method can be made easier through the use of Prime Factorization. Prime Factorization is a program that can assist you in the factoring of numbers in Algebra, namely trinomials using the AC Method. It can also find all the factors of any number.PromedioNotas: El programa trata de promediar 3 nostas y mostrar y si pasaba de año o no por medio de un mensajeProyecto Tarea: Este proyecto esta hecho con el objetivo de aprender sobre TFSProyectotarea1: Sotfware de terminal aéreo de Guayaquil, donde se encuentran el nombre de las aerolíneas y las rutas de vuelo a nivel nacional.Python: this is the Python project.Ruby: this is the Ruby project.tedplay: tedplay is your media player of choice for playing Commodore 264 music format files similar to SIDplay. It is basically a stripped down Commodore plus/4 emulator without video output and peripherals based on the SDL build of the Commodore 264 family emulator YAPE. tedplay is released under version 2 of the GNU Generic Public License and can be built for both Windows and Unix or actually any platform that has a C++ compiler and SDL support.test1: This is a test projectwin-x264: A port of the x264-codebase into a VisualStudio-project. Compilation requires Intel-compiler and Yasm.XDA ROM Hub: Xperia 2011 line toolkit.znvicente_cuartoc: Poyecto Vicente Eduardo Zambrano Navarrete??Win7?????: ??????? *.theme ???????(??,??,??,???)。????VSB???*.msstyles??,????????,????????????????????????!????????????,?????????????。???,????????! ?????????,?????????,????????,??????!?????????????,?????????????????,?????????,???Aero??,??????~?????????????!??,?????????theme??,?????????,??????,????,??????。 This program used to create .theme file and the relevant documents (wallpaper, pointer, ICONS, sounds, etc.). As long as you use VSB ready . msstyles files, chosen the icon wallpaper, etc, an...

    Read the article

  • Adding local users / passwords on Kerberized Linux box

    - by Brian
    Right now if I try to add a non-system user not in the university's Kerberos realm I am prompted for a Kerberos password anyway. Obviously there is no password to be entered, so I just press enter and see: passwd: Authentication token manipulation error passwd: password unchanged Typing passwd newuser has the same issue with the same message. I tried using pwconv in the hopes that only a shadow entry was needed, but it changed nothing. I want to be able to add a local user not in the realm and give them a local password without being bothered about Kerberos. I am on Ubuntu 10.04. Here are my /etc/pam.d/common-* files (the defaults that Ubuntu's pam-auth-update package generates): account # here are the per-package modules (the "Primary" block) account [success=1 new_authtok_reqd=done default=ignore] pam_unix.so # here's the fallback if no module succeeds account requisite pam_deny.so # prime the stack with a positive return value if there isn't one already; # this avoids us returning an error just because nothing sets a success code # since the modules above will each just jump around account required pam_permit.so # and here are more per-package modules (the "Additional" block) account required pam_krb5.so minimum_uid=1000 # end of pam-auth-update config auth # here are the per-package modules (the "Primary" block) auth [success=2 default=ignore] pam_krb5.so minimum_uid=1000 auth [success=1 default=ignore] pam_unix.so nullok_secure try_first_pass # here's the fallback if no module succeeds auth requisite pam_deny.so # prime the stack with a positive return value if there isn't one already; # this avoids us returning an error just because nothing sets a success code # since the modules above will each just jump around auth required pam_permit.so # and here are more per-package modules (the "Additional" block) # end of pam-auth-update config password # here are the per-package modules (the "Primary" block) password requisite pam_krb5.so minimum_uid=1000 password [success=1 default=ignore] pam_unix.so obscure use_authtok try_first_pass sha512 # here's the fallback if no module succeeds password requisite pam_deny.so # prime the stack with a positive return value if there isn't one already; # this avoids us returning an error just because nothing sets a success code # since the modules above will each just jump around password required pam_permit.so # and here are more per-package modules (the "Additional" block) # end of pam-auth-update config session # here are the per-package modules (the "Primary" block) session [default=1] pam_permit.so # here's the fallback if no module succeeds session requisite pam_deny.so # prime the stack with a positive return value if there isn't one already; # this avoids us returning an error just because nothing sets a success code # since the modules above will each just jump around session required pam_permit.so # and here are more per-package modules (the "Additional" block) session optional pam_krb5.so minimum_uid=1000 session required pam_unix.so # end of pam-auth-update config

    Read the article

  • Monitor and Terminate Python script based on system resource use

    - by Vincent
    What is the "right" or "best" way to monitor the system resources a python script is using and terminate it if the resource use exceeds some predetermined values. In my case memory usage is of concern. I am not asking how to measure the system resource use although I am open to suggestions. As a simple example, let's assume I have a function that finds prime numbers less than some large number and adds them to a list based on some condition. I don't know ahead of time how many prime numbers will satisfy the condition so I what to be sure to terminate the function if I use up to much system memory (8gb lets say). I know that there are ways to monitor the size of python objects. What I don't know is the proper way to monitor the size of the list and exit is to just include a size test in the prime function loop and exit if it exceeds 8gb or if there is an "external" way to monitor and exit.

    Read the article

  • Highest value datatype can store in c#

    - by user472832
    I am writing a small program for my assignment to find the primitive roots of a prime number. So far, the program works for smaller prime numbers till 13 and gives correct number of roots. But for higher primes numbers, it is showing only fewer primitive roots. And now i got stuck for the prime number 41, shows no primitive roots for it. I used DOUBLE datatype for the calculation, and again tried with the datatype DECIMAL, but no luck. Does anyone know about this kind of problem??? Thank you.

    Read the article

  • Java random values and duplicates

    - by f-Prime
    I have an array (cards) of 52 cards (13x4), and another array (cardsOut) of 25 cards (5x5). I want to copy elements from the 52 cards into the 25 card array by random. Also, I dont want any duplicates in the 5x5 array. So here's what I have: double row=Math.random() *13; double column=Math.random() *4; boolean[][] duplicates=new boolean[13][4]; pokerGame[][] cardsOut = new pokerGame[5][5]; for (int i=0;i<5;i++) for (int j=0;j<5;j++){ if(duplicates[(int)row][(int)column]==false){ cardsOut[i][j]=cards[(int)row][(int)column]; duplicates[(int)row][(int)column]=true; } } 2 problems in this code. First, the random values for row and column are only generated once, so the same value is copied into the 5x5 array every time. Since the same values are being copied every time, I'm not sure if my duplicate checker is very effective, or if it works at all. How do I fix this?

    Read the article

  • Code igniter authentication code in controller security question

    - by Prime Studios
    I have a main controller to handle the very front-end of my authentication system, it handles login, logout, update user info, etc. functions that I anticipate calling by POST'ing from views/forms. What about something like a "delete_user" function though? My thoughts are a button in someones admin panel would say "Delete Account" and it would post to "/auth/delete", and the function would delete the user based on their session username or id. This seems a bit open ended, you could send out a link to someone and when they opened it while in that application it would delete their account.. Whats the best way to handle this?

    Read the article

  • How do you specify a really large character in UIButton?

    - by Epsilon Prime
    I have a series of buttons that have suit symbols on them. Currently I provide these suit symbols as bitmaps. In preparation for iPhone 4 I'd like to use text instead. However Interface Builder rescales the button to account for whitespace underneath the symbol so I can't get the image to fill the button completely. Any hints on getting Interface Builder to behave?

    Read the article

  • Prefix and Postfix operator's necessity

    - by Karthi prime
    What is the necessity of both prefix and postfix increment operators? Is not one enough? To the point, there exists like a similar while/do-while necessity problem, yet, there in no so much confusion (in understanding and usage) in having them, but with having both prefix and postfix (like priority of these operators, their association, usage, working). And do anyone been through a situation where you saidd "Hey, I am going to use postfix increment. Its useful here"

    Read the article

  • Mathematica Programming Language&ndash;An Introduction

    - by JoshReuben
    The Mathematica http://www.wolfram.com/mathematica/ programming model consists of a kernel computation engine (or grid of such engines) and a front-end of notebook instances that communicate with the kernel throughout a session. The programming model of Mathematica is incredibly rich & powerful – besides numeric calculations, it supports symbols (eg Pi, I, E) and control flow logic.   obviously I could use this as a simple calculator: 5 * 10 --> 50 but this language is much more than that!   for example, I could use control flow logic & setup a simple infinite loop: x=1; While [x>0, x=x,x+1] Different brackets have different purposes: square brackets for function arguments:  Cos[x] round brackets for grouping: (1+2)*3 curly brackets for lists: {1,2,3,4} The power of Mathematica (as opposed to say Matlab) is that it gives exact symbolic answers instead of a rounded numeric approximation (unless you request it):   Mathematica lets you define scoped variables (symbols): a=1; b=2; c=a+b --> 5 these variables can contain symbolic values – you can think of these as partially computed functions:   use Clear[x] or Remove[x] to zero or dereference a variable.   To compute a numerical approximation to n significant digits (default n=6), use N[x,n] or the //N prefix: Pi //N -->3.14159 N[Pi,50] --> 3.1415926535897932384626433832795028841971693993751 The kernel uses % to reference the lastcalculation result, %% the 2nd last, %%% the 3rd last etc –> clearer statements: eg instead of: Sqrt[Pi+Sqrt[Sqrt[Pi+Sqrt[Pi]]] do: Sqrt[Pi]; Sqrt[Pi+%]; Sqrt[Pi+%] The help system supports wildcards, so I can search for functions like so: ?Inv* Mathematica supports some very powerful programming constructs and a rich function library that allow you to do things that you would have to write allot of code for in a language like C++.   the Factor function – factorization: Factor[x^3 – 6*x^2 +11x – 6] --> (-3+x) (-2+x) (-1+x)   the Solve function – find the roots of an equation: Solve[x^3 – 2x + 1 == 0] -->   the Expand function – express (1+x)^10 in polynomial form: Expand[(1+x)^10] --> 1+10x+45x^2+120x^3+210x^4+252x^5+210x^6+120x^7+45x^8+10x^9+x^10 the Prime function – what is the 1000th prime? Prime[1000] -->7919 Mathematica also has some powerful graphics capabilities:   the Plot function – plot the graph of y=Sin x in a single period: Plot[Sin[x], {x,0,2*Pi}] you can also plot 3D surfaces of functions using Plot3D function

    Read the article

  • Project Euler 3: (Iron)Python

    - by Ben Griswold
    In my attempt to learn (Iron)Python out in the open, here’s my solution for Project Euler Problem 3.  As always, any feedback is welcome. # Euler 3 # http://projecteuler.net/index.php?section=problems&id=3 # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number # 600851475143? import time start = time.time() def largest_prime_factor(n): max = n divisor = 2 while (n >= divisor ** 2): if n % divisor == 0: max, n = n, n / divisor else: divisor += 1 return max print largest_prime_factor(600851475143) print "Elapsed Time:", (time.time() - start) * 1000, "millisecs" a=raw_input('Press return to continue')

    Read the article

  • Handling large integers in python [migrated]

    - by Sushma Palimar
    I had written a program in python to find b such that a prime number p divides b^2-8. The range for b is [1, (p+1)/2]. For small integers it works, say only up to 7 digits. But not for large integers, say for p = 140737471578113. I get the error message for i in range (2,p1,1): MemoryError I wrote the program as #!/usr/bin/python3 p=long(raw_input('enter the prime number:')) p1=long((p+1)/2) for i in range (2,p1,1): s = long((i*i)-8) if (s%p==0): print i

    Read the article

  • How well does Ubuntu run on the ASUS Eee tablet?

    - by Const
    I'm considering buying an ASUS Eee Transformer Prime. I mainly want it so I can do some light web coding on the go. I commute a lot and most of my time is spent on the trains unfortunately. I know that it is possible to install Ubuntu on the transformer prime. I'm also aware that it is not stable since its something new. I'm wondering if anyone has tried it, how responsive/ fast is it? Does the batter die quickly?

    Read the article

  • SAP rachète Sybase pour 4.6 milliards d'euros, quels changements pour le marché des logiciels ?

    SAP rachète Sybase pour 4.6 milliards d'euros, quels changements pour le marché des logiciels ? SAP, groupe allemand numéro un mondial des logiciels de gestion, vient de réaliser une grosse opération. Il vient en effet de racheter son concurrent américain Sybase (numéro quatre mondial des logiciels de bases de données) pour la coquette somme de 5.8 milliards de dollars (4.6 milliards d'euros). La transaction, qui n'a pas encore été effectuée et devrait être finalisée courant septembre 2010, consistera en le rachat par SAP des actions en numéraire de Sybase (65 dollars chaque, ce qui représente une prime de 44% par rapport au cours moyen de l'action sur trois mois et une prime avoisinant les 16% sur le cours de clôture de l'entrepr...

    Read the article

  • Advanced Django query with subselects and custom JOINS

    - by Bryan Ward
    I have been investigating this number theoretic function (found in the Height model) and I need to query for things based on the prime factorization of the primary key, or id. I have created a model for Factors of the id which maintains all of the prime factors. class Height(models.Model): b = models.IntegerField(null=True, blank=True) c = models.IntegerField(null=True, blank=True) d = models.FloatField(null=True, blank=True) class Factors(models.Model): height = models.ForeignKey(Height, null=True, blank=True) factor = models.IntegerField(null=True, blank=True) degree = models.IntegerField(null=True, blank=True) prime_id = models.IntegerField(null=True, blank=True) For example, if id=24, then the associated entries in the factors table would be height_id=24,factor=2,degree=3,prime_id=0 height_id=24,factor=3,degree=1,prime_id=1 the prime_id keep track of the relative order of the primes. Now let p < q < r < s all be prime numbers and a,b,c,d be positive integers. Then I want to be able to query for all Heights of the form id=(p**a)*(q**b)*(r**c)*(s**d). Now this is simple in the case that all of p,q,r,s,a,b,c,d are known in that I can just run Height.objects.get(id=(p**a)*(q**b)*(r**c)*(s**d)) But I need to be able to query for something like (2**a)*(3**2)*(r**c)*(s**d) where r,s,a,d are unknown and all Heights of such form will be returned. Furthermore, not all of the rows in Height will have exactly four prime factors, so I need to make sure that I am not matching rows of the form id=(p**a)*(q**b)*(r**c)*(s**d)*(t**e)... From what I can tell, the following MySQL query accomplishes this, but I would like to do it through the Django ORM. I also don't know if this MySQL query is the proper way to go about doing things. SELECT h.*,count(f.height_id) AS factorsCount FROM height AS h LEFT JOIN factors AS f ON ( f.height_id = h.id AND f.height_id IN (SELECT height_id FROM factors where prime_id=1 AND factor=2 AND degree=1) AND f.height_id IN (SELECT height_id FROM factors where prime_id=2 AND factor=3 AND degree=2) AND f.height_id IN (SELECT height_id FROM factors where prime_id=3 AND factor=5 AND degree=1) AND f.height_id IN (SELECT height_id FROM factors where prime_id=4 AND factor=7 ANd degree=1) ) GROUP BY h.id HAVING factorsCount=4 ORDER BY h.id; Any ideas or suggestions for things to try?

    Read the article

  • How to make efficient code emerge through unit testing

    - by Jean
    Hi, I participate in a TDD Coding Dojo, where we try to practice pure TDD on simple problems. It occured to me however that the code which emerges from the unit tests isn't the most efficient. Now this is fine most of the time, but what if the code usage grows so that efficiency becomes a problem. I love the way the code emerges from unit testing, but is it possible to make the efficiency property emerge through further tests ? Here is a trivial example in ruby: prime factorization. I followed a pure TDD approach making the tests pass one after the other validating my original acceptance test (commented at the bottom). What further steps could I take, if I wanted to make one of the generic prime factorization algorithms emerge ? To reduce the problem domain, let's say I want to get a quadratic sieve implementation ... Now in this precise case I know the "optimal algorithm, but in most cases, the client will simply add a requirement that the feature runs in less than "x" time for a given environment. require 'shoulda' require 'lib/prime' class MathTest < Test::Unit::TestCase context "The math module" do should "have a method to get primes" do assert Math.respond_to? 'primes' end end context "The primes method of Math" do should "return [] for 0" do assert_equal [], Math.primes(0) end should "return [1] for 1 " do assert_equal [1], Math.primes(1) end should "return [1,2] for 2" do assert_equal [1,2], Math.primes(2) end should "return [1,3] for 3" do assert_equal [1,3], Math.primes(3) end should "return [1,2] for 4" do assert_equal [1,2,2], Math.primes(4) end should "return [1,5] for 5" do assert_equal [1,5], Math.primes(5) end should "return [1,2,3] for 6" do assert_equal [1,2,3], Math.primes(6) end should "return [1,3] for 9" do assert_equal [1,3,3], Math.primes(9) end should "return [1,2,5] for 10" do assert_equal [1,2,5], Math.primes(10) end end # context "Functionnal Acceptance test 1" do # context "the prime factors of 14101980 are 1,2,2,3,5,61,3853"do # should "return [1,2,3,5,61,3853] for ${14101980*14101980}" do # assert_equal [1,2,2,3,5,61,3853], Math.primes(14101980*14101980) # end # end # end end and the naive algorithm I created by this approach module Math def self.primes(n) if n==0 return [] else primes=[1] for i in 2..n do if n%i==0 while(n%i==0) primes<<i n=n/i end end end primes end end end

    Read the article

  • Fastest primality test

    - by Grigory Javadyan
    Hi. Could you suggest a fast, deterministic method that is usable in practice, for testing if a large number is prime or not? Also, I would like to know how to use non-deterministic primality tests correctly. For example, if I'm using such a method, I can be sure that a number is not prime if the output is "no", but what about the other case, when the output is "probably"? Do I have to test for primality manually in this case? Thanks in advance.

    Read the article

  • what should be the return type of the hashCode()

    - by subhashis
    The signature of the hashCode() method is public int hashCode(){ return x; } in this case x must be an int(primitive) but plz can anyone explain it to me that the number which the hashCode() returns must be a prime number, even number...etc or there is no specification ? the reason behind i am asking this question is i have seen it in different ids the auto generated code always returns a prime number, so i need to know why? thanks in advance

    Read the article

  • Is there any way to maximize PHP_INT_MAX?

    - by Tom
    I can't find this row in php.ini, so is there any way to do that? So ok, I understood, the answer is not, then how should I calculate the result of this task if I want it do with php? The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

    Read the article

  • Mutable objects and hashCode

    - by robert
    Have the following class: public class Member { private int x; private long y; private double d; public Member(int x, long y, double d) { this.x = x; this.y = y; this.d = d; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = (int) (prime * result + y); result = (int) (prime * result + Double.doubleToLongBits(d)); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Member) { Member other = (Member) obj; return other.x == x && other.y == y && Double.compare(d, other.d) == 0; } return false; } public static void main(String[] args) { Set<Member> test = new HashSet<Member>(); Member b = new Member(1, 2, 3); test.add(b); System.out.println(b.hashCode()); b.x = 0; System.out.println(b.hashCode()); Member first = test.iterator().next(); System.out.println(test.contains(first)); System.out.println(b.equals(first)); System.out.println(test.add(first)); } } It produces the following results: 30814 29853 false true true Because the hashCode depends of the state of the object it can no longer by retrieved properly, so the check for containment fails. The HashSet in no longer working properly. A solution would be to make Member immutable, but is that the only solution? Should all classes added to HashSets be immutable? Is there any other way to handle the situation? Regards.

    Read the article

  • Problems with usually short solutions to test in a programming language

    - by sub
    I'm currently creating an experimental programming language for fun and educational purpose and in search for some tasks beyond the classical "Hello, World!"-program. I've already come up with these ideas: Print out the program's input Calculator Generate Prime numbers, Fibonacci series What other interesting programming problems do you have for me to test? It would be good if they required the language to solve a broad spectrum of task, take prime numbers for example: You need variables, increment them, divide them, perform actions under certain conditions, etc.

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >